Friday, January 22, 2016

PHP MYSQL: Display Records in Table From Database

Data is essential in an organization. So storing it in a database helps an organization to easily store it so they can retrieve it in the near future for decision-making. All information systems have the following common functions, to add or insert new record, update existing record, view list of records in the database and delete records. If you are going to create one, all you have to do is to reuse your codes since they are all the same. They just differ in the name of table, column names and variable names.

I already provided a tutorial on how to insert records in the database. This time, I will teach you how to display records from database to a table. Before you start, first create your database and table like on the picture below.


First you construct  your HTML code and insert the following code between your body code.

HTML, PHP and MySQL Code
<th>ID #</th> 
<th>Last Name</th> 
<th>First Name</th> 
$con = mysqli_connect("localhost","root","","elearning"); 

$result=mysqli_query($con,"select * from student order by stud_last")or die(mysqli_error());
<td><?php echo $row['stud_id'];?></td>
<td><?php echo $row['stud_last'];?></td>
<td><?php echo $row['stud_first'];?></td>
<?php }?>

I will discuss the php code one by one. First line of code is your database connection. You will find the hostname, username, password, database name. Next line is your query to display all (*) records from the table student and arrange it according to stud_last name. If order is not specify, the default ordering is in ascending order. ASC for ascending and DESC for descending are the keywords used after the clause ORDER BY to specify how the database engine will sort the records.

Since you want to display the records in table, you need to echo the data in between the <td></td> tag. The closing curly brace (}) should be put after the </tr> to loop the rows instead of columns.

Output Display Record in Table

Hope this helps! Good day! ^_^

Feel free to comment below for questions. 

PHP MYSQL: Display Data in Tables From Database

No comments:

Post a Comment