PHP : Select Rows from MySQL ( mysqli and PDO)

1. Connect and fetch rows from MySQL : mysqli (OOPS)

<?php
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$dbname = 'university';
$db= new  mysqli($host,$user,$pass,$dbname);
// check connection sucess		 
if ( ! $db->connect_error) 
{
echo 'Connection established  sucessfully...';

 $sql="SELECT * FROM teacher";
 
 
 $result = $db->query($sql);
 
 while( $row =  $result->fetch_assoc())
 {
  echo  "<br/>".$row['T_code']."|".$row['T_Name']."|".$row['T_Dept']."|".$row['T_Subject'];
 }
 
 $db->close();
}
else
{
echo 'The connection to the database could not be established.';
}
?>

2. Connect and fetch rows from MySQL : mysqli (Procedural)

<?php
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$dbname = 'university';
$db = mysqli_connect($host, $user, $pass, $dbname);
if(mysqli_connect_errno())
{
    die('The connection to the database could not be established.');
}
else
{
	  echo " Connection established  sucessfully...";
      $sql="SELECT * FROM teacher";
 	 $result=mysqli_query($db,$sql);
  	  while( $row = mysqli_fetch_assoc($result))
	  {
	  echo  "<br/>".$row['T_code']."|".$row['T_Name']."|".$row['T_Dept']."|".$row['T_Subject'];
	  }
	  
 mysqli_close();
 ?>
}

3. Connect and fetch rows from MySQL : PDO (PHP Data Object)

<?php
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$dbname = 'university';
try
{
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
echo " connection established  sucessfully...";
$sql="SELECT * FROM teacher";
$result=$db->query($sql);

$result->setFetchMode(PDO::FETCH_ASSOC);

     while($row = $result->fetch())
     {
		 echo  "<br/>".$row['T_code']."|".$row['T_Name']."|".$row['T_Dept']."|".$row['T_Subject'];
	 }
	 
$db->close();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

4. Here is MySQL Database

12may_1

Posted in PHP