Home PHP Basics Retrieving Data from MySql into HTML Table Using PHP

Relevant sites

Retrieving Data from MySql into HTML Table Using PHP PDF E-mail
Thursday, 24 July 2008 06:36

In last article I explained how to make a connection to MySql server and how to create a MySql database using PHP. This article is continuation of last article.

Use following link to visit that article

Connecting To MySql Server Using PHP

In this article I will populate an HTML table by retrieving data from “student” table created in last article.

 

Insert Data into MySql Table

Data can be inserted in to table using standard query language(SQL). This process is simple and easy to understand. PHP provides standard mechanism for all DML operations. For example we use Mysql_query() function to make an insertion, updation or deletion. We will examine this with following example

First we will insert data into “student” table.

Following code inserts 3 row into table.

<?php

$connect = mysql_connect("localhost", "root", "password") or

die ("Error, check your server connection.");

mysql_select_db("school");

$insert="insert into student values (1,'Jones','8th'),(2,'Raymon','8th'),(3,'Michle','8th')";

$results=mysql_query($insert) or die(mysql_error());

echo "Data Inserted Successfully";

?>


In above code first we wrote a query to insert three rows and stored it in $insert variables. In next line mysql_query() function executed the query and inserted rows into database.

 



Populating HTML Table

To retrieve data from MySql server we use mysql_fetch_array(). This function takes a query as parameter and retrieves a result set in the form of an array. We can use loop to traverse through the array.


<?php

$connect = mysql_connect("localhost", "root", "password") or

die ("Hey loser, check your server connection.");

mysql_select_db("school");

$quey1="select * from student";

$result=mysql_query($quey1) or die(mysql_error());

?>

<table border=1 style="background-color:#F0F8FF;" >

<caption><EM>Student Record</EM></caption>

<tr>

<th>Student ID</th>

<th>Student Name</th>

<th>Class</th>

</tr>

<?php

while($row=mysql_fetch_array($result)){

echo "</td><td>";

echo $row['stud_id'];

echo "</td><td>";

echo $row['stud_name'];

echo "</td><td>";

echo $row['stud_class'];

echo "</td></tr>";

}

echo "</table>";

?>

In above example While loop traverse through result set and on each iteration of loop we used HTML table tags to create a HTML table.

Final output of the above script will look like as

Student Record
Student ID Student Name Class
1Jones8th
2Raymon8th
3Michle8th



Last Updated on Friday, 31 July 2009 07:45