background
|
|
Tombstone
Tombstone Tuning
Home of tuning, projects and fast cars and boats.
More icon

Games
Ruffnecks Gaming Gaming for everyone
More

Tombstone
Tombstone Tuning Home of tuning, projects and fast cars and boats.
More
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
PHP/MySQL Tutorial
Lesson 2

by Graeme Merrall

Page 2 — Stay Informed

Take a look at this script.




<html>



<body>



<?php



$db = mysql_connect("localhost", "root");

mysql_select_db("mydb",$db);

$result = mysql_query("SELECT * FROM employees",$db);

if ($myrow = mysql_fetch_array($result)) {

  echo "<table border=1>\n";

  echo "<tr><td>Name</td><td>Position</td></tr>\n";

  do {



    printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["first"], $myrow["last"], $myrow["address"]);

  } while ($myrow = mysql_fetch_array($result));

	echo "</table>\n";

} else {

	echo "Sorry, no records were found!";	

}



?>



</body>



</html>



There are a number of new features introduced here, but they're quite simple. First, there's the mysql_fetch_array() function. This is exactly the same as mysql_fetch_row() with one nice exception: Using this function, we can refer to fields by their names (such as $myrow["first"]) rather than their numbers. This should save us some headaches. We've also introduced a do/while loop and an if-else statement.

The if-else statement says that if we can assign a row to $myrow, then continue; otherwise skip to the else section and do what's in there.

The do/while loop is a variation of the while() loop we used on the last page. We need the do/while loop here for a very good reason: With the initial if statement, we assigned the first row returned by the query to the variable $myrow. If at this point we executed a regular while statement (such as while ($myrow = mysql_fetch_row($result)), we'd be kicking the first record out of the variable and replacing it with the second record. But the do/while loop lets us test the condition after the code has been run once. So there's no chance of us accidentally skipping a row.

Finally, if there are no records returned at all, the statements contained in the else{} portion will be executed. To see this portion in action, change the SQL statement to SELECT * FROM employees WHERE id=6 or something else that will return no records.

Now let's extend this looping and if-else code to make one fancy-schmancy page. You're going to love it.

next page»