An introduction to PHP and MySQL

In this guide I'm going to describe how to get started with PHP and MySQL. Many books have been written on this subject, but I'm just going to cover the basics of getting connected to a MySQL database and executing simple queries. This assumes that you've set up a MySQL database and have the proper privileges necessary to run the queries you prefer. This also assumes that you have a basic understanding of how to create and run a PHP script.

1

<?php
$link = mysql_connect( 'localhost', 'username', 'password' );
if ( ! $link ) die( mysql_error() );

The first line simply opens the PHP script and allows the interpreter to know that PHP is contained within.

The next line actually makes the connection to the database. The first parameter is a string containing the hostname, the second parameter is a string containing the username, then the third parameter is a string containing the password. A successful connection will return a resource containing the mysql connection. Any connection problem will simply return false.

The third part checks for a false link and prints the mysql error if there is one.

2

$db = mysql_select_db( 'database_name' );
if ( ! $db ) die( mysql_error() );

The first line selects a specified database and returns false if there is a problem. The first parameter to 'mysql_select_db' is a string containing the database name.

The second part, like the previous step, simply checks for a false response signifying an error.

3

$res = mysql_query( "select * from table_name" );
if ( ! $res ) die( mysql_error() );

This line actually runs a mysql query. To start I recommend running a select query like the one provided in the example. To run a query you will need to know the name of the table. This function returns a mysql resource containing the query results.

As before, if this function returns false, there was an error so we will stop the script.

4

if ( mysql_num_rows( $res ) > 0 ) {
   while ( $row = mysql_fetch_array( $res ) ) {
      print_r( $res );
   }
}
?>

The first line is a condition testing the number of rows return by the query. If there is more than one row we will continue.

The second part contained within the conditional is a while loop that will loop through each of the results of the query result. 'mysql_fetch_array' is a function that takes each row of the mysql resource response and converts it into a PHP array.

Finally, the third part contained within the loop will simply print the PHP array so we can see the contents.