You are on page 1of 11

Connect to MySQL database from PHP

MySQL and PHP are two technologies used by many web developers. Connecting to MySQL from PHP is easy and when we consider that both PHP and MySQL are free technologies, the pair sounds like winning choice. This article shows how to connect to MySQL with PHP. The PHP script below simply connects to a MySQL database and then immediately closes the connection. Of course you will want to do more than that reading, updating, inserting and deleting data, but once you are connected to the db, these tasks are easy.
"; $password = ""; $hostname = "localhost"; $database = ""; $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_close($conn); ?>

Now that you have connected to the MySQL server from your PHP script, how do you select which database to work with (there can be more than one database on the same MySQL server)? Here is how to select a MySQL database to work with, from PHP:
"; $password = ""; $hostname = "localhost"; $database = ""; $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); mysql_close($conn); ?>

Now that we have selected a MySQL database, we can retrieve some data from it and send it back to the browser from our PHP script:
"; $password = ""; $hostname = "localhost"; $database = ""; $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed");

mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); $sSQL = "SELECT FirstName, LastName FROM Users"; $result = mysql_query($sSQL, $conn); while($row = mysql_fetch_object($result)) { echo $row->FirstName . " " . $row->LastName . " "; } mysql_close($conn); ?>

In the PHP script above we are connecting to MySQL database, selecting data with mysql_query and printing it to the browser.

PHP MySQL
This page introduces PHP calls to MySQL and is the second half of the forms page of this document showing a display of available databases or database tables.
PHP MyAdmin

You can use PHP calls to MySQL to set up your database, but there is an easier way. There is a tool called "PHP MyAdmin". It makes it very easy to create the databese, set up tables, and fields. After the initial setup is done, then I use PHP calls to MySQL to manage the database by retrieving values from it, changing values, or deleting entries. You can get more information at http://www.phpmyadmin.org.
PHP MySQL Calls

Most commonly used PHP calls to MySQL include:

bool mysql_create_db This function tries to create a new database associated with the optional resource link identifier. The syntax is:

bool mysql_create_db( string database name [, resource link_identifier]); An example is: $status = mysql_create_db($dbname);

mysql_connect - Opens a connection to the database. An example statement is:

$chandle = mysql_connect("localhost", $dbuser, $dbpass);

mysql_select_db - Selects the database to be associated with the database handle (link identifier) which is the second parameter passed to the function. An example statement is:

$boolval=mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found." . $dbuser);

QUERY Statement - The query statement is used to send queries to the database. The most commonly queries are SELECT, DELETE, UPDATE, and INSERT. In my code, I used mysql_db_query, but this statement is depreciated. You should be able to use the statement mysql_query, without the database name string. Just remember that the query will be to the last selected database or last queried database. An example statement is:

$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); This statement relies on the query statement provided above as "$query1". There are several types of queries which can be performed using mysql_db_query or mysql_query. Some of the commonly used ones are.
o

Select - Used to get information from the database. This statement will return the contents of all matching database entries.

$query1="select * from " . $mainsection . " as t1 where t1.idname = " . "\"" . $section2 . "\" The variable "$mainsection" is the name of the table the delete operation will be performed on. The item t1 is used to identify the database fields and idname is the name of one of the fields. The variable "$section2" is a string that the value in the idname field is to match in order to qualify the database entry for retrieval into the result value when the query call is done. When inside quotes ("..."), use of \" is used to place a quote in a query statement which is how this is used in the above statement.
o

Delete - Used to remove a database entry. An example query statement using delete is:

$query1="delete from " . $mainsection . " where id = " . $value; The variable "$mainsection" is the name of the table the delete operation will be performed on. The id is a database field used as a unique identifier.
o

Update - Used to change the value of a field one or more database entries. An example query statement using update is:

$newval = 1; $query1="update " . $mainsection . " set dbflag=" . $newval . " where id = " .

$value; The variable "$mainsection" is the name of the table the delete operation will be performed on. The dbflag is a database field which is being set to a value of 1.
o

Insert - Used to add a new database entry to the database. Any field value not specified here will be set to the default value for the field. An example query statement using insert is:

$query1="insert into " . $mainsection . " (url, sitetitle, description, gifurl, cat1, email, creator, id, entdate, sitetype) values (\"" . $url . "\",\"" . $title . "\",\"" . $description . "\",\"" . $gifurl . "\",\"" . $category . "\",\"" . $email . "\",\"" . $uname . "\"," . $i2 . ", CURDATE()," . $stype . ")";

mysql_fetch_row - Used to get the results of a query row by row. An example is

$thisrow=mysql_fetch_row($result) The above statement will only return one row or returned database entry. The value returned is an array of field values in the database. The example below will read all the returned rows and print the field names and values out.
while($thisrow=mysql_fetch_row($result)) { $i=0; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo $field_name . "=" . $thisrow[$i] . "<br>"; $i++; } }

mysql_close - Used to close the database. An example:

mysql_close($chandle);

PHP MYSQL Example


Below is an example of how to use the mysql functions supported by PHP to access a MySQL database. Here is the file "dblist.php".
<?php session_start(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="description" content="Database List"> <title>Database List</title> </head> <body> <?php if ($location1=="database") { $chandle = mysql_pconnect("localhost", $username, $password) or die("Connection Failure to Database"); session_register("database"); $database=$QUERY_STRING; // The database name is passed using QUERY_STRING mysql_select_db($database, $chandle) or die ("Database not found."); $tablelist=mysql_list_tables($database); echo "<H3>Available Tables in the ", $database, " Database:</H3>"; echo "<UL>"; $table = 0; while ($table < mysql_num_rows($tablelist)) { $tablename=mysql_tablename($tablelist, $table); echo "<LI><A href=\"dblist.php?", $tablename, "\">", $tablename, "</A><BR>"; $table++; } echo "</UL>"; mysql_close($chandle); $location1="table"; } elseif ($location1=="table") { $chandle = mysql_pconnect("localhost", $username, $password) or die("Connection Failure to Database"); mysql_select_db($database, $chandle) or die ("Database not found."); $query1="select * from " . $QUERY_STRING; $result = mysql_db_query($database, $query1) or die("Failed Query"); $i=0; echo "<table rules=\"all\"><tr>"; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo "<th>", $field_name->name, "</th>"; $i++; } echo "</tr>"; while ($thisrow=mysql_fetch_row($result)) //get one row at a time { echo "<tr>"; $i=0; while ($i < mysql_num_fields($result)) //print all items in the row { echo $thisrow[$i], "<br>"; $i++; } echo "</tr>";

} echo "</table>"; mysql_free_result($result); mysql_close($chandle); } ?> </body> </html>

The value of location1 is initialized in the file in section 9 called "Using PHP with Forms". It is passed using sessions, and is used to tell if we are showing the available databases or tables. Its value is initally "database" then it is changed to "table". In this example one feature is that two strings are added using the period sign. Here's the line that adds the strings: $query1="select * from " . $QUERY_STRING; Mysql functions that are used include:

$chandle = mysql_pconnect("localhost", $username, $password) - Used to connect to the server. mysql_select_db($database, $chandle) - Used to select the default database to query. $tablelist=mysql_list_tables($database) - Used to get a list of tables that are available in the database. This list is a dimensioned string and the following two functions are used to list the names of the tables: o mysql_num_rows($tablelist) - Indicates the number of items in the tablelist string. o $tablename=mysql_tablename($tablelist, $table); - This is used to get the name of the table from the string of availabel tables using the table list reference and the index value. $result = mysql_db_query($database, $query1) - Used to send a query to the database. o mysql_num_fields($result) - Used to determine the number of fields in the query result. o field_name=mysql_fetch_field($result, $i); - Used to get the field object (not the name) for the query with the specified index. o $thisrow=mysql_fetch_row($result); - Used to get the entire row. This is a string array. mysql_free_result($result); - Frees the memory occupied by the $result string. mysql_close($chandle); - Closes the connection to the mysql database server.

Although it is functional, this file is not nearly complete. It does not allow for multiple queries based on one login. Additional controls should be added to make this example completely functional.

PHP SQL Connect


This statement opens a connection to the database server. The "mysql_connect" or "mysql_pconnect" statements may be used to do this. I recommend that the "mysql_connect"

statement be normally used except for special circumstances. This is because the "mysql_pconnect" statement is used to establish a permanent connection to the database. The "mysql_close" statement will NOT end connections opened with the "mysql_pconnect" statement. If you use the "mysql_pconnect" statement to connect to your database on your website, you may start getting errors stating that you have too many connections open to the database and additional connections will be refused.
PHP SQL Connect Statement Syntax

The syntax for the mysql_connect statement is shown below. This statement will open a connection to the server. The "mysql_select_db" statement must be used later to select the database on the server to be used. resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])
PHP SQL Connect Statement Example

In this example, a connection is made to the database using the user called "username", with a passsword of "password". You will want to use a unique password. The name "localhost" is used to specify that the database is on the same server that the PHP program is running on. This is your webserver. The handle to the database is returned in the variable "$chandle". If the call fails, the string contained after the "or die" part of the statement will be executed and program execution will stop.
$dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); echo "Connected to database server<br>"; mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found." . $dbuser); echo "Database " . $database . " is selected"; mysql_close($chandle);

PHP SQL Select Database


PHP SQL Select DB Statement Syntax

The syntax for the mysql_select_db statement is shown below. This statement will select the database that future queries will be sent to. bool mysql_select_db ( string database_name [, resource link_identifier]) The value returned is true if there is success, and it is false if the command failed.

PHP SQL Select DB Statement Example


$dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); echo "Connected to database server<br>"; mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found." . $dbuser); echo "Database " . $database . " is selected"; mysql_close($chandle);

PHP SQL Select Query and Getting rows


The SQL query statement is uset to access the database. It can be used to read the database or write to the database. This page discusses the use of the query statement to read the database. The PHP MySQL introduction page explains some query call types and what they are used forhere.
PHP SQL Query Statement Syntax

There are two query statements which may be used, they are mysql_db_query and mysql_query. The statement mysql_db_query is depreciated and it is recommend that the mysql_query statement is used. The syntax for both statements is shown below. resource mysql_db_query ( string database, string query [, resource link_identifier]) resource mysql_query ( string query [, resource link_identifier])
PHP SQL Query Statement Example

The below example performs a query looking for an idname called "Home" in the database table "sections".
$dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser); $mainsection="sections"; //The name of the table $query1="select * from " . $mainsection . " as t1 where t1.idname = " . "\"Home\""; //select the home section $result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query $thisrow=mysql_fetch_row($result);

if ($thisrow) //if the results of the query are not null { echo "The Home section was found.<br>"; } else { echo "The Home section was not found.<br>"; }

When a query is done, the results can be placed in a specific order. The example below shows how to do this using the order by phrase. When the query is done with a "order by" sort, the results will be displayed in the order requested.
$dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser); $mainsection="links"; //The name of the table where web links are stored $query1="select * from " . $mainsection . " as t1 where ((t1.active and t1.approved) and (t1.cat1 = \"" . $section . "\" or t1.cat2 = \"" . $section . "\" or t1.cat3 = \"" . $section . "\")) order by t1.score DESC, t1.hits DESC"; //select all approved links that belong to the current category $result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query while($thisrow=mysql_fetch_row($result)) { $i=0; while ($i < mysql_num_fields($result)) { $field_name=mysql_fetch_field($result, $i); echo $thisrow[$i] . " "; //Display all the fields on one line $i++; } echo <br>"; //put a break after each database entry }

PHP SQL Delete Query


The delete query is used to delete entries from the database. The below example shows how this is done.
$dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass)

or die("Connection Failure to Database"); mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser); $mainsection="links"; //The name of the table where web links are stored $idno=10; $query1="delete from " . $mainsection . " where id = " . $idno; mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); echo "Link with ID " . $idno . " has been deleted as requested.<br>"; }

The delete item is chosen by inique id number, "$idno", which in this case is set to 10. The table the entry is deleted form is the "links" table which is where internet links are stored.

PHP SQL Insert Query


The insert query is used to add entries to the database. Any field value not specified here will be set to the default value for the field. The below example shows how this is done. In my example, I am creating a web site that is a directory of web links. The database to support this effort includes the following fields:

url - The internet address of the web page referenced. sitetitle - The title of the web page referneced. description - The description of the web page referenced. gifurl - The optional internet address of a graphic url to be displayed with the link. cat1 - The category the link belongs in email - The email of the link creator. creator - The alias of the link creator. id - The unique id value of the link. entdate - The date the link was created. sitetype - The type of site this is such as commercial, educational, or government.

The code below creates a new entry into my database setting values as shown. The values of $ure, $title, $description, $gifurl, $category, $email. $uname, and $stype were created earlier from a form submission. These values are automatically available to the PHP page processing the form input. The CURDATE() function generates a date string with a value of the current date. $dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser); $mainsection="links"; //The name of the table where web links are stored $query1="insert into " . $mainsection . " (url, sitetitle, description, gifurl, cat1, email, creator, id,

entdate, sitetype) values (\"" . $url . "\",\"" . $title . "\",\"" . $description . "\",\"" . $gifurl . "\",\"" . $category . "\",\"" . $email . "\",\"" . $uname . "\"," . $i2 . ", CURDATE()," . $stype . ")"; mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1);

PHP SQL Update Query


In this example a delete flag is cleared associated with a database entry is cleared. $dbuser="username"; $dbpass="password"; $dbname="mydata"; //the name of the database $chandle = mysql_connect("localhost", $dbuser, $dbpass) or die("Connection Failure to Database"); mysql_select_db($dbname, $chandle) or die ($dbname . " Database not found. " . $dbuser); $mainsection="links"; //The name of the table where web links are stored $deletef=0; $query1="update " . $mainsection . " set deletef=" . $deletef . " where id = " . $delete_link[$i1]; mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); echo "Link with ID " . $delete_link[$i1] . " has had the delete flag cleared and will not be deleted.<br>";

You might also like