Displaying table from MySql database using php

To display a table using php first we need to create a database using mysql and then we need to create a table inside the database. For this, I have used WAMP server because it is relatively easy to create a database.

If you don't have WAMP Server, you can download it from here.

Now, here are the steps to create a database.

1) Go to your phpMyAdmin page.


2) Click on "Databases". This page will give you the option of creating a new database and it will also show you the existing database in your server.

3) After creating your database, you will be asked to create a table. Create your table with the no. of columns you desire giving them your desired data type which depends on the type of data you are willing to store in the columns fo eg: text,integer and so on.

4) After creating your table, you will need to insert data into the table by using the following sql queries.

INSERT INTO TABLE_NAME VALUES("COL1","COL2",....);



Note : No need to give " " for integer fields. Replace your own table name with "TABLE_NAME".

5) Go on inserting data into table as much as you like.

6) Now you need to write the php file to make a connection with the database and display the table on your web browser.

For this I have used a database name "produce" and table name "fruit" with fields name(text), number(integer) and quantity(text).

Here is the php file for the program.

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("SELECT * FROM fruit");
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"
             </td><td>",$row['quantity'],"</td>";
     echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?>   

Note : The default username for WAMP Server is "root" and no default password is given so I have used " " as password while making connection with the database.       
    
Here is the output of the php file.

NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
     

Top