Loading

Sunday, February 10, 2008

Connecting to MySQL

In order to access and make use of a MySQL database, you first must create a database and then create and manage a set of tables within that database. In order to connect to your database, however, you must also create a user that has permissions to access the database in question, and assign them a password. For the following examples, I have created a database called taskdb. I have also assigned a user called apressauth to the database and given the user a password: tasks. In order to perform this sort of database management, you can go ahead and use the command line interface MySQL provides, or try a more robust solution. I prefer phpMyAdmin (www.phpmyadmin.net) for a web-based solution and SQLyog (www.webyog.com/sqlyog) for remote connections. Both are free solutions and will serve you well.
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.

SHARE TWEET

Thank you for reading this article Connecting to MySQL With URL http://x-tutorials.blogspot.com/2008/02/connecting-to-mysql.html. Also a time to read the other articles.

0 comments:

Write your comment for this article Connecting to MySQL above!