Pages

Friday, October 29, 2010

Reading MySQL Data

So, you've connected to the database, created your table, and inserted some data into that table. Now what do you do with it? Well, you read the data from the table and display on your website, using the following code:
$rows = 20;  // the number of table rows to display

// read data from database
$result = mysql_query("select * from $table order by id desc limit $rows", $link)
or die ("Could not read data because ".mysql_error());

// print the data in a table
if (mysql_num_rows($result)) {
print "<table cellpadding=2 cellspacing=0 border=0 width=\"100%\">\n";
while ($qry = mysql_fetch_array($result)) {
print "<tr><td><a href=\"" . "$qry[email]\" target=\"_blank\">$qry[name]</a>: ";
print $qry[comment];
print "</td></tr>\n";
}
print "</table>\n";
}
With mysql_query we select all the entries in the table and order them by their $id number. We also limit the displayed entries to the number defined in the $rows variables, so in this case, only 20 entries will be displayed.

Next, we count the rows and display them in a table. The while() loop says "for each new row to display, assign that row to an array called $qry;" we do this so we can continue to print out $qry until there are no rows left. If you're wondering what an "array" is, it's a group of variables, and in this script, name, email and comment are all part of the $qry array, which is why we call them as $qry[name] and $qry[email] instead of $name and $email.

After we've finished with our MySQL connection, we close it.
mysql_close();
And that is all the code you'll need for a simple MySQL guestbook script! If you have trouble putting it together, take a look at all the code.

0 Comments:

Post a Comment