Friday, April 3, 2015

Check If A Database Exists In Php

To to convenience a database with PHP, connect to the database server and then unlocked the database you yearning to utilize. You can accomplish both of these tasks using built-in PHP functions designed to grindstone with the database engine, For instance MySQL. In both cases, you should analysis the go back payment from the avail phone to conclude if they were successful. For an unsuccessful function call, check the specific error code generated to determine the cause of the error.}


?>4. Exit the editor and save the program.



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


php checkdb.php


2. 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 instance, type:



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


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


3. 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!");


else


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


}


else {


echo "Database exists!";


For instance, MySQL will issue error code 1146 if a database does not exist.

Instructions

1.


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.