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. |
STUDENT Table |
First you construct your HTML code and insert the following code between your body code.
HTML, PHP and MySQL Code
<table>
<tr>
<th>ID #</th>
<th>Last Name</th>
<th>First Name</th>
</tr>
<?php
$con = mysqli_connect("localhost","root","","elearning");
$result=mysqli_query($con,"select * from student order by stud_last")or die(mysqli_error());
while($row=mysqli_fetch_array($result)){
?>
<tr>
<td><?php echo $row['stud_id'];?></td>
<td><?php echo $row['stud_last'];?></td>
<td><?php echo $row['stud_first'];?></td>
</tr>
<?php }?>
</table>
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.
No comments:
Post a Comment