pTutorial

New way to learn PHP

PHP 5 MYSQL select data from table

How to retrieve data from table

After inserting data into table we will use SELECT statement extract data from the table.

Syntax

SELECT * FROM table_name;

Another syntax

SELECT field1, field2... FROM student;
  • You can specify one or more in a single SELECT statement.
  • You can use * to retrieve all the field.

Complete example of SELECT data FROM table


<?php
$host = 'localhost';
$user = 'root';
$password = "";
$db_con = mysql_connect($host, $user, $password);
if($db_con)
{
echo "Connected successfully<br>";	
}
else
{
echo "fail";	
}
$b = mysql_select_db("my_db1");
$data = "select *from student";
$data1 = mysql_query($data,$db_con)or die(mysql_error());

while($row = mysql_fetch_array($data1)) 
{
	echo "------------------------<br>";
    echo $row['id']."<br>";
    echo $row['name']."<br>";
    echo $row['branch']."<br>";
    echo "------------------------";
    echo "<br>";
}
 
mysql_close();
?>

Output

Connected successfully
------------------------
1
Brown
Ece
------------------------
------------------------
2
xyz
ma
------------------------
------------------------
3
harry
cse
------------------------

mysql_fetch_array() function is used to assign an entire row to an associative array by default. However, you can specify the type of array mapping (associative, numerically indexed).

Another example


<?php
$host = 'localhost';
$user = 'root';
$password = "";
$db_con = mysql_connect($host, $user, $password);
$b = mysql_select_db("my_db1");
$data = "select name, branch from  student";
$data1 = mysql_query($data,$db_con)or die(mysql_error());

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

    echo $row['name']."<br>";
	echo "<br>"."<br>";
}
 
mysql_close();
?>


Explanation

$row is an array type variable that store the all the data of table, you can access data using field value as key as above shown in example.


QUOTES OF THE DAY

The basis of all progress is self-reliance

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER