PHP & MySQL

This is an example using PHP and MySQL using the MySQLi extension together. The first thing to do is to establish a connection to your database using PHP.


1
23
45
67
89
$host = 'mysql.example.com'; #the URL of the database
$user = 'anonymous'; #the username for the database $pass = 'password'; #whatever the password is
$db_name = 'datebaseName'; #name of database being connected to 
$mysqli = new mysqli($host,$user,$pass,$db_name);               if($mysqli->connect_error){
                die('Connection error: ('.$mysqli->connect_errno.'): '.$mysqli->connect_error);        }

Line 6 establishes a new MySQLi object. For simplicity I call it mysqli, you can name it anything you wish. It is usually a good idea to check to make sure that the connection to the database was successful, and if not tell you why it was not. This was done in lines 7 through 9.

Next you need to query the database using the MySQLi object.

1
23
45
67
8
$query = "SELECT field1, field2, field3 FROM MyTable"; #this is what you are wanting from your database
$result = $mysqli->query($query); #here we use the MySQLi object and run the function query on it#To make our lives easier, we put this into a variable, which then can be as an object.
 #Then return the results in some fashion. The cleanest way is to use a while loop.
while($row = $result->fetch_assoc()){ #MySQLi's fetch_assoc() places each row in an associative array.   echo $row['field2']." ,".$row['field1']." ".$row['field3']; 
   }

One nice thing about using fetch_assoc, is that you can refer to the rows by the field names, versus what order they may appear in the array and using that index.

The following is from the database with some formatting

May 27, 2009

this is a test of my new code


Oct 9, 2007

This is Doctor XYZ, specializing in CP.


Aug 14, 2007

You know, when you have such a simple form, it makes updating a website easy, unless the database corrupts. All you need to know is a few HTML tags, and there you go!


© Ryan E. Benson 2006 - 2018
Updated on: 03/14/2010 21:07:32 - Chat with Ryan