How to display data from a MySQL database – PHP Script

PHP is the very wide used and easiest language in the world.

It’s very simple to display the data from a MySQL table to a webpage using PHP scripting.

First you need to create a database and a table in mysql. You can learn by watching this video or Click here to Read an Article.

After you create a database and a table. You insert some values in it.

Lets say our table is look like this now:

Database name:    mydatabase
Table name:           mytable

Id

name

city

1

Agurchand

Bangalore

2

Abhiesheik

Chennai

3

Balaji

Madurai

Then use the below code to fetch records from the database and show it on the webpage!


<?php

//Syntax: mysql_connect('hostname', 'username', 'password');
//Connect to a db: mysql_select_db('dbname');

$con = mysql_connect( 'localhost', 'root', 'root' );
$db =  mysql_select_db( 'mydatabase' );

//now write a select query to fetch the records from the table

$sql = "select * from mytable";
$query = mysql_query( $sql );

echo "<table>";

//now read and display the entire row of a table one by one looping through it.
//to loop we are using While condition here

while( $row = mysql_fetch_assoc($query) )
{
echo "<tr><td>$row[id]</td></tr>";
echo "<tr><td>$row[name]</td></tr>";
echo "<tr><td>$row[city]</td></tr>";
}

echo "</table>";

?>

 

Enjoy learning new things daily. Practical Experiment is the only way of learning stuffs quickly and powerfully.

4 Comments

Leave a Reply