How to Check if a Database Exists in PHP


To to use a database with PHP, connect to the database server and then open the database you want to use. You can accomplish both of these tasks using built-in PHP functions designed to work with the database engine, for example MySQL. In both cases, you should check the return value from the function call to determine if they were successful. For an unsuccessful function call, check the specific error code generated to determine the cause of the error. For example, MySQL will issue error code 1146 if a database does not exist.

  • Create a new PHP program file in an editor. For example, type:

    php checkdb.php

  • Connect to the database server with the host, username and password. Check the return value to determine if the database server connection was successful. For example, type:


    $dbc = mysql_connect("localhost", "username", "password");

    if (!$dbc) die("Could not connect to database server!");

  • Call the function to select the database and evaluate the return value. If the selection was not successful, check to see if the error code is "1049," indicating that the database does not exist. Write the appropriate message to the screen depending on the result of the database function call. For example, type:

    $db = mysql_select_db("database");

    if (!$db) {

    if (($err = mysql_errno()) == 1049)

    die("Database does not exist!");


    die("Database exists but there is another error " . $err . " - " . mysql_error($db));


    else {

    echo "Database exists!";



  • Exit the editor and save the program. Run the PHP program by navigating to it in a browser. Test that the program is working correctly by opening a database that exists and attempting to open a database that does not exist.

Related Searches


Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!