PHP-MySQL Lesson: Select Data in Database and Display the record in HTML table

PHP-MySQL Lesson: Select Data in Database and Display the record in HTML table

In this lesson we are going to write PHP scripts that select records in MySQL database and display it in HTML table.

The SELECT statement in sql is used to select a record in the database. In PHP, mysql_query() function is used to execute SELECT query.Here is the code: save it as php_select.php

<?php
//including the database connection file
include("mysql_connect.php");
mysql_select_db("employee");
$result = mysql_query("SELECT * FROM employee_record");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Position</th>
<th>Age</th>
<th>Salary</th>
<th>Email</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['f_name']."</td>";
echo "<td>".$row['l_name']."</td>";
echo "<td>".$row['position']."</td>";
echo "<td>".$row['age']."</td>";
echo "<td>".$row['salary']."</td>";
echo "<td>".$row['email']."</td>";
echo "</tr>";
}
echo "</table>";
?>

In the above example it will display the records in an HTML table.

In our example we have used include() function, this function takes all the content in a specified file and includes it in the current file.

Then, we have selected the employee database using the mysql_select_db() function.

Next, we have declared a variable $result that will store the value returned by mysql_query() function.

Next, we use the mysql_fetch_array() function to fetch a row from a recordset as an array.

Then, we place the mysql_fetch_array() function within the conditional statement of the while loop. It means that the while loop will continue to execute as long as there a row to fetch.

, ,

Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.