PHP to view data from MySQL

Records that have been stored in the database are needed to be access in order to be display on the monitor so that the user can view it. PHP and MySQL are capable of storing as well as retrieving of data that are stored in database. The example code below is a PHP code that can retrieve data to the MySQL database and display it on the browser. It can help to new programmer who wants to learn PHP and MySQL database web programming.

Let assume that the database name use is “mydatabae” and the table name is “Persons” with the following fields personID, FirstName, and Age. The PHP code will connect to the database using the password “root” without a password. After the connection to database it will select all the records stored in the table person and display the result to the browser. PHP code is use to manipulate the data stored in the MySQL database and HTML is use to format the output.

Aside from the database function such as add, edit, and delete, the function on how to retrieve data is important so that data that are keep in database can be used for future purposes. The PHP code below illustrates on how to retrieve data from a database.

The PHP code:
File Name: view.php

$con = mysql_connect("localhost","root","");
if (!$con)
  die('Could not connect: ' . mysql_error());

mysql_select_db("mydatabase", $con);

$result = mysql_query("SELECT * FROM Persons");

echo "<table border='1'>

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>";


Related article: PHP code to add data to database