MySQLi Select

MySQL SELECT statement is used to fetch data from Table.

Syntax

SELECT [Fields] FROM Tablename [WHERE CLAUSE] [LIMIT];

These are the following ways to select data from a table.

Object Oriented PHP MySQLi Select Data


The following code select data from a table in object oriented way -


<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
$select = "SELECT * FROM `employee` ";
$result = $conn->query($select);
if($result->num_rows > 0){
 echo '<table>';
 echo '<tr><td>Employee Name</td>'; 
 echo '<td>Email</td>'; 
 echo '<td>Phone</td>';  
 echo '<td>Address</td>';  
 echo '</tr>';
 while($row = $result->fetch_object()){
   echo '<tr>';  
   echo '<td>'. $row->emp_name.'</td>';
   echo '<td>'. $row->email.'</td>';
   echo '<td>'. $row->phone.'</td>';
   echo '<td>'. $row->address.'</td>';
   echo '</tr>';
 }
 echo '</table>';
}
?>




Procedural PHP MySQLi Select Data


<?php
$conn = mysqli_connect('hostname', 'username', 'password', 'databasename');
//Check for connection error
if(mysqli_connect_error()){
  die("Error in DB connection: ".mysqli_connect_errno()." - ".mysqli_connect_error());
}
$select = "SELECT * FROM `employee` ";
$result = mysqli_query($conn, $select);
if(mysqli_num_rows($result)){
 echo '<table>';
 echo '<tr><td>Employee Name</td>'; 
 echo '<td>Email</td>'; 
 echo '<td>Phone</td>';  
 echo '<td>Address</td>';  
 echo '</tr>';
 while($row = mysqli_fetch_object($result)){
   echo '<tr>';  
   echo '<td>'. $row->emp_name.'</td>';
   echo '<td>'. $row->email.'</td>';
   echo '<td>'. $row->phone.'</td>';
   echo '<td>'. $row->address.'</td>';
   echo '</tr>';
 }
 echo '</table>';
}
?>   
    




Prepared PHP MySQLi Select Statement


<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
$empname = 'John';
$query = "SELECT emp_id, emp_name, email, phone, address FROM employee WHERE emp_name =? ";
$select = $conn->prepare($query);
// bind parameters 
$select->bind_param('s',$empname);
//execute query
$select->execute();
//bind the result variables 
$select->bind_result($emp_id, $emp_name, $email, $phone, $address);
 echo '<table>';
 echo '<tr><td>Employee Id</td>'; 
 echo '<td>Employee Name</td>'; 
 echo '<td>Email</td>'; 
 echo '<td>Phone</td>';  
 echo '<td>Address</td>'; 
 echo '</tr>';
 while($select->fetch()){
   echo '<tr>';  
   echo '<td>'. $emp_id.'</td>';
   echo '<td>'. $emp_name.'</td>';
   echo '<td>'. $email.'</td>';
   echo '<td>'. $phone.'</td>'; 
   echo '<td>'. $address.'</td>'; 
   echo '</tr>';
 }
 echo '</table>';
?>