Connecting to a Database with PHP
page 1: Introduction
page 2: Connecting to the Database
page 3: Displaying Tables
page 4: Inserting New Records
page 5: Updating Records
page 6: Deleting Records
Display selected contents of a DB table
Let's do something a little more useful, like actually displaying some data from our selected database. After establishing the connection to, and then selecting the database as before, we'll issue a query using the SQL language. Our new function is called mysql_query. If you recall the fields of the adoption_list table that we created in the animal_rescue database, you can decide which ones you want to display in the browser. We probably don't want to display the ID, and for now, let's skip the image field. The syntax for selecting the fields we want from a particular table are actually much like natural language. (Note: If you just wanted to display every field of the database, you could use the wildcard * (asterisk) which stands for all.) Notice that connection identifier showing up again though? And of course, we put all of this into a variable I called $resultID so we can use it "in shorthand" later in the script.
It is time to actually “echo” or print the information to the browser. All we have going on here is HTML table code. You'll notice that each of the table cell headers contains the name of a different field we want to display. To get each unique record to display, we're going to use the “while” programming loop and another mysql function, mysql_fetch_row. All this means is that while there is still another new record in the table, that a new row gets generated to display it in our HTML table. When there are no more new records, the loop ends. See if you can figure out how the different variables are used to create shortcuts in the code. (Please refer to the source code, as this script has line breaks to permit displaying within this page.)
<?php
$connectID=mysql_connect("localhost", "root", "yourpasswordhere");
mysql_select_db("animal_rescue", $connectID);
$resultID = mysql_query("SELECT species, breed, name, age, personality
FROM adoption_list", $connectID);
print "<table border=1><tr><th>Species</th><th>Breed</th>
<th>Name</th><th>Age</th><th>Personality</th></tr>";
while ($row=mysql_fetch_row($resultID))
{
print "<tr>";
foreach ($row as $field)
{
print "<td>$field</td>";
}
print "</tr>";
}
print "</table>";
mysql_close($connectID);
?>

This is what our script will output to the browser. If you go to View
Source, all you will see is the HTML, not the php script we wrote.
Inserting New Records-->>