Home >>MySQL Tutorial >PHP MySQL Select

PHP MySQL Select

PHP MySQL Display Data

The SELECT statement is used to display data from a table.

To display all data from a table use select(*) statement and to display particular field's data use select filed1,filed2 at the place of (*).

Syntax
 SELECT  column1, column2, column3,... FROM table_name
//OR
SELECT * FROM table_name		
Ex(PHP MySQL Display Data)
<?php
//connect database 
$con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error());
//select all values from empInfo table
$data="SELECT * FROM empInfo";
$val=mysqli_query($con,$data);
while($r=mysqli_fetch_array($val))
{
echo $r['emp_id']." ".$r['name']." ".$r['email']." ".$r['mobile']."<br/>";
}				
?>
The example above stores the data returned by the mysql_query( ) function in the $data variable. Next, we use the mysql_fetch_array( ) function to return the first row from the recordset as an array. Each call to mysql_fetch_array( ) returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $r variable ($r['emp_id'], $r['name'],$r['email'] and $r['mobile']).

Select values from table using list( ) function

<?php
//connect database 
$con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error());
	
//select all values from empInfo table
$data="SELECT * FROM empInfo";
$val=mysqli_query($con,$data);
			
while(list($id,$name,$eid,$mob) = mysqli_fetch_array($val))
{
 echo $id." ".$name." ".$eid." ".$mob."<br/>";
}		
?>
The example above stores the data returned by the mysql_query( ) function in the $data variable. Next, we use the mysql_fetch_array( ) function to return the first row from the recordset as list($id,$name,$eid,$mob) funtion in variable $id,$name,$eid,$mob. 1st field values stored in $id, 2nd in $name, 3rd in $eid and 4th values in $mob . Now print variables $id, $name, $eid, $mob.

Display the Records inside Table

<?php
//connect database 
$con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error());
//select values from empInfo table
$data="SELECT * FROM empInfo";

$val=mysqli_query($con,$data);			
echo "<table border='1'>";
echo "<tr><th>Emp_id</th><th>Name</th><th>Email</th><th>Mobile</th></tr>";
while(list($id,$name,$eid,$mob)= mysql_fetch_array($val))
{
 echo "<tr>";	
 echo "<td>".$id."</td>";
 echo "<td>".$name."</td>";
 echo "<td>".$eid."</td>";
 echo "<td>".$mob."</td>";
 echo "</tr>";
}		
echo "</table>";		
?>

No Sidebar ads