Changes

Jump to: navigation, search

Using PHP with MySQL

2,592 bytes added, 14:59, 7 June 2007
Inserting Data into a MySQL Database Table
3 rows in set (0.00 sec)
</pre>
 
== Connecting wiht PHP to a MySQL Server ==
 
Now that we have set upo our MySQL databse and entered some data it is time to look at using PHP to connect to the database so that we can start to query the database and add new data. The first step in our PHP script is to connect to our MySQL database server. This is achieved using the PHP ''mysql_connect()'' function. The ''mysql_connect()'' function creates a connection to the database server and returns a database resource handle. The function takes five optional arguments. The first is the address of the server hosting the database. This defaults to ''localhost:3306''. The second argument is the user name to be used to connect to the database. The third argument is the password associated with the user name.
 
If a second call is made to ''mysql_connect()'' the default behavior is to return the handle from the first call. Setting the fourth argument overrides this behavior and generate a new handle.
 
The final argument represents the flags for the PHP client which works in the background to connect to the database. Options are MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE and MYSQL_CLIENT_INTERACTIVE.
 
To disconnect form the database use the ''msql_close()'' function which takes as a sole argument the datbase resource handle returned by ''mysql_connect()''.
 
We can now write a script which will connect us to our sample database (remember to modify the password to match the one you specified when creating the user account):
 
<pre>
<?php
 
$dbhandle = mysql_connect('localhost', 'phptest', '3579php');
 
if ($dbhandle)
{
echo "Connected to MySQL Database<br>";
mysql_close($dbhandle);
 
} else {
echo "Unable to connect to MySQL Database<br>";
}
 
 
?>
</pre>
 
== Selecting Records from a MySQL Database Using PHP ==
 
Now tghat we have connected to our MySQL database we can begin accessing the data in our table. To achieve this we need to first select the database we wish to use by calling the ''mysql_select_db()'' function, passing through the database name as an argument. This will return a database handle. We then need to construct a SQL SELECT statement which we will pass to the PHP ''mysql_query()'' function. This function takes the database handle (returned by ''mysql_select_db()'') and the SQL query statement as arguments.
 
The ''mysql_query()'' function call places the results in an array which we can access using the ''mysql_fetch_array()'' function.
 
Bringing this all together gives us the following:
 
<pre>

Navigation menu