SEARCH
Newsletter
Subscribe to get design
tips, latest trends, free
stuff and more.
It doesn't look like an e-mail address

hosting

  Web Programming PHP Retrieving data from a database

Retrieving data from a database

SweDesignz.com PHP Jun 09, 2006

Retrieving Data From a DatabaseBefore getting started, I'll assume you already 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>

   
subscribe to newsletter