How to Select and Display mysql table data using Select Query

PHP Select query is used to retrieve data from mysql table and display using the echo() php function.

Here is a  simple PHP code  that  can  be embedded in HTML and can be used to display table data.

If we have a table customers that has the following fields

Customer Id,Firstname,SecondName and Phone Number

Those are the values that we need retrieved from the database and displayed by php in form of a table

1.First we need to connect to a mysql database.See my previous post about connecting to a mysql database here

here is the code to connect to mysql database


<?php
// Connects to your Database
if(!defined('INCLUDE_CHECK')) die("not allowed to execute directly");

 

$host="127.0.0.1";

$username="root";
$password="password"; // Mysql password
$db="db_name";

 

$link=mysql_connect($host,$username,$password) or die(mysql_error());

mysql_select_db($db,$link);
mysql_query("SET names UTF8");

?>

2.Once connected.,excute the select command


$sql="SELECT*FROM Customers";

$rs=mysql_query($sql);

The above code will select all the table data name “Customers” and assign the result value to a Php Variable $rs

3.The next step is to assing the values returned into a multidimensionl array


$array=mysql_fetch_row($rs);

4.Once all the values have been assigned to a multidimensional array they can be displayed using a while loop

 

while ($array=mysql_fetch_row($rs))
{

echo '<tr style="background-color:#CCCCCC">';
echo'<td class="a-center"><font size="2">'.$row[0].'</font></td>';

echo'<td> <font size="2">'.$row[1].'</font></td>';

echo' <td><font size="2">'.$row[2].'</font></td>';
echo'<td><a href="#"><font size="2">'.$row[3].'</font></a></td>';

echo '</tr>';
}

 

About the Author: Eric K

My name is Eric.Am a software developer with skills in Php,Mysql, Java , Android,Node.js Above all, I have certification in Cisco Networking Associate (CCNA) and holds degree in Information Technology. Hire me: Email : kawi3462@gmail.com