To connect to a MySQL database using PHP, you must make use of the mysql_connect function. Consider the following code, found within the file dbconnector.php, that will allow you to connect to the database:
//dbconnector.php
//Define the mysql connection variables.
define ("MYSQLHOST", "localhost");
define ("MYSQLUSER", "apressauth");
define ("MYSQLPASS", "tasks");
define ("MYSQLDB", "taskdb");
function opendatabase(){
$db = mysql_connect (MYSQLHOST,MYSQLUSER,MYSQLPASS);
try {
if (!$db){
$exceptionstring = "Error connecting to database:
";
$exceptionstring .= mysql_errno() . ": " . mysql_error();
throw new exception ($exceptionstring);
} else {
mysql_select_db (MYSQLDB,$db);
}
return $db;
} catch (exception $e) {
echo $e->getmessage();
die();
}
}
?>
As you can see, there are two parts to any database connection using MySQL. First, the mysql_connect function must attempt to make a connection to the database and validate the username and password. If a valid connection is made, a connection to the server will be retained. At this point, you must now specify which database you want to be working on. Since there could potentially be many databases assigned to each MySQL user, it is imperative that the script know which database to use. Using the mysql_select_db function, you can do just that. If everything goes properly, you should now have an open connection to the database, and you are ready to move on to the next stop: querying the database.
0 comments:
Post a Comment