Thursday, August 1, 2013

How to retrieve data from database through PHP with and without table?

The SELECT statement is used to select data from a database:

Syntax
SELECT column_name(s)
FROM table_name

Working code (without table) is:

<?php
$con = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error()); 
  mysql_select_db(“againtest", $con);
$result = mysql_query("SELECT * FROM Person");
while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'] . " " . $row['Age'];
  echo "<br>";
  }
mysql_close($con);
?>

We have established connection and save it in con variable. Then we selected the database from where we want to retrieve data. In our case it is "againtest". mysql_query() is a function that takes query as a parameter and returns result in $result (my own defined variable). As there might be more than one rows fetched from table, so we applied while loop which will keep traversing this variable till reaching the last result. For fetching row one by one from the group of rows ($result ) , mysql_fetch_array() is used. This function extracts one row at a time and save it in $row variable. Information of this row is displayed through echo function. It will continue working until or unless it reaches to last result.

Output will be like this:

Now if we want to display the same data in tabular form, then we will have to embed html code for table in this. Look the following code for this:

<?php
$con = mysql_connect("localhost","root","")or die('Could not connect: ' . mysql_error()); 
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age']. "</td>";
  echo "</tr>";
  }
echo "</table>";
mysql_close($con);

?> 
Now output will be like this:

This code is in running form. I hope you will have good understanding of displaying data through PHP and HTML now. 

1 comment:

  1. I know this if off topic but I'm looking into starting my own weblog and was curious what all is required to get set up?
    I'm assuming having a blog like yours would cost a pretty penny?
    I'm not very internet savvy so I'm not 100% certain. Any tips or advice would be greatly appreciated.
    Kudos

    Feel free to surf to my page; minecraft games

    ReplyDelete