Retrieving Data From A Database

Tutorial Description:
Learn how to use PHP to retrieve information & data from a database.
Before getting started, I’ll assume you already read the Database Connection tutorial and know how to connect & select the database of your choose.
Retrieving data from a database is a common task for web database applications, the most common use is to display the data in a web page.
To get the data from the database, we’ll need to use the SELECT command.
OK, lets say we have a table named “pets”, containing pets names, types…etc
We want to display all the dogs within our page. Pay attention to the code comments.
<?php
// we'll select all the information in the database for five dogs.
$query = "SELECT * FROM pets
WHERE type = 'dog'
LIMIT 5";
// actually execute the query.
$result = mysql_query($query);
?>
Now that we got the information, we’ll need to display it:
<?php
// for every dog we selected, run the following block.
while ($row = mysql_fetch_array($result))
{
// display information for each dog.
echo "Name: $row[name], Age: $row[age], Breed: $row[breed] ";
}
?>
We’ve retrieved the data and displayed it. Of course you should make nicer, but you get the idea.
You can see the full script below:
<html>
<head>
<title>Dogs</title>
</head>
<body>
<?php
// connect to database.
include("connect.php");
// we'll select all the information in the database for five dogs.
$query = "SELECT * FROM pets
WHERE type = 'dog'
LIMIT 5";
// actually "do" the query.
$result = mysql_query($query);
// for every dog we selected, run the following block.
while ($row = mysql_fetch_array($result))
{
// display information for each dog.
echo "Name: $row[name], Age: $row[age], Breed: $row[breed] ";
}
?>
</body>
</html>

