Web Info and IT Lessons Blog...

Sunday, 31 May 2015

Select data from MySql database in PHP

The previous lesson of PHP Lessons Series was about watermarking images in php and in this lesson we will learn to select data from a MySql database using PHP.

MySql Select Data in PHP

Let us say we have a MySql test database (testdb) containing a table (student) shown in the image below and we want to select the data of all students and show it to the user.

MySql Student Table

The above image shows the student table containing (Name, Standard, Marks) of the students. Now let us write a PHP code to select all the data from student table and show it to the user.

The first thing we need to do here is make a connection to MySql Database in PHP in a separate PHP file and then include the database connection file in our main index file. Once we have successfully made connection to our MySql Database then all we need to do is select data from MySql table and show it in PHP.

dbconnection.php

<?php

$dbhost = "localhost";
$dbusername = "root";
$dbpass = "";
$dbname = "testdb";

$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if($connection){
 echo "Database Connection Successful.";
 if(mysql_select_db($dbname)){
  echo 'Database Selected Successfully.';
 }else{
  echo 'Database does not exist.';
 }
}else{
 echo "Error Connecting to Database.";
}

?>

index.php

<?php

include 'dbConnection.php';

$query = "SELECT * FROM student WHERE 1=1";
if($query_run = mysql_query($query)){
 While($rows = mysql_fetch_assoc($query_run)){
  echo 'Name: '.$rows['Name'].' Marks'.$rows['Marks'].' Standard'
                      .$rows['Standard'].'<br />';
 }
}else{
 echo "Error Running Query.";
} 

?>

The above PHP code will select all the data from student table and display it in PHP. To do the same task using mysqli extension consider the code given below:

dbconnection.php

<?php

$dbhost = "localhost";
$dbusername = "root";
$dbpass = "";
$dbname = "testdb";

$connection = mysqli_connect($dbhost, $dbusername, $dbpass);
if($connection){
 echo "Database Connection Successful.";
 if(mysqli_select_db($connection,$dbname)){
  echo 'Database Selected Successfully.';
 }else{
  echo 'Database does not exist.';
 } 
}else{
 echo "Error Connecting to Database.";
}

?>

index.php

<?php

include 'dbConnection.php';

$query = "SELECT * FROM student WHERE 1=1";
if($query_run = mysqli_query($connection,$query)){
 While($rows = mysqli_fetch_assoc($query_run)){
  echo 'Name: '.$rows['Name'].' Marks'.$rows['Marks'].' Standard'
                     .$rows['Standard'].'<br />';
 }
}else{
 echo "Error Running Query.";
}

?>

Stay tuned for more lessons...

No comments:

Post a Comment