Thursday, October 12, 2017

PHP Select Data From MySQL Database


In this article, we are going to learn how to select records from database table using PHP Script. To select records from database table we are using PHP mysqli_query() function. This function is used to perform query operation in MySQL database.

NOTE : mysql_query() function is deprecated, since PHP 5.5 Version.
               mysqli_connect() function is not available form PHP 7

There are two other MySQLi functions used to retrieve data from MySQL Database:
  1. mysqli_num_rows(mysqli_result ): returns number of rows from database.
  2. mysqli_fetch_assoc(mysqli_result ): returns row as an associative array. Each key of the array represents the column name of the table. It return NULL if there are no more rows.
Here we are trying to retrieve below records from MySQL query :

PHP MySQLi Select Query Example

<?php  
$host = 'localhost';  // set the hostname
$user = '';  // set the mysql username
$pass = '';  // set the mysql password
$dbname = 'companyrecord';  
//establish the database connection  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected to database successfully<br/>';  
// mysql query to select record  
$sql = 'SELECT * FROM employee';  
$retval=mysqli_query($conn, $sql);  
  
if(mysqli_num_rows($retval) > 0){  
 while($row = mysqli_fetch_assoc($retval)){  
    echo "EMP ID :{$row['id']}  <br> ".  
         "EMP NAME : {$row['empname']} <br> ".  
         "EMP SALARY : {$row['empsalary']} <br> ".  
         "--------------------------------<br>";  
 } 
}else{  
echo "No results found";  
}  
mysqli_close($conn);  
?>

Output:
-----------------------
Connected to database successfully
EMP ID :1
EMP NAME : sumit
EMP SALARY : 4400
--------------------------------
EMP ID :2
EMP NAME : amit
EMP SALARY : 232000
--------------------------------
EMP ID :3
EMP NAME : kisan
EMP SALARY : 23000
--------------------------------


3 comments:

  1. For example if you were running a company and selling a product you may have a database that simply lists all of the sales you have made over a period of time. create mysql dashboard

    ReplyDelete