Fetch data using PHP


Retrieving data from some database is very easy in PHP. Using a MySQL database, we will retrieve the information from the database table we created called “friends”

// Collects data from "friends" table
 $data = mysql_query("SELECT * FROM friends")
 or die(mysql_error()); 

And we will then temporarily put this information into an array to use:

// puts the "friends" info into the $info array
 $info = mysql_fetch_array( $data );

Now let’s print out the data to see if it worked:

// Print out the contents of the entry
 Print "<b>Name:</b> ".$info['name'] . " ";
 Print "<b>Pet:</b> ".$info['pet'] . " <br>";

However this will only give us the first entry in our database. In order to retrieve all the information, we need to make this a loop. Here is an example:

while($info = mysql_fetch_array( $data ))
 {
 Print "<b>Name:</b> ".$info['name'] . " ";
 Print "<b>Pet:</b> ".$info['pet'] . " <br>";
 } 

So let’s put all the these ideas together to create a nicely formatted table with this final php code:

 <?php
 // Connects to your Database
 mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
 mysql_select_db("Database_Name") or die(mysql_error());
 $data = mysql_query("SELECT * FROM friends")
 or die(mysql_error());
 Print "<table border cellpadding=3>";
 while($info = mysql_fetch_array( $data ))
 {
 Print "<tr>";
 Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
 Print "<th>Pet:</th> <td>".$info['pet'] . " </td></tr>";
 }
 Print "</table>";
 ?> 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s