PHP : Inserting new row to MySQL ( mysqli and PDO)

1. insert row :  mysqli (OOPS)

<?php
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$dbname = 'university';

$db= new  mysqli($host,$user,$pass,$dbname);
if ( ! $db->connect_error) 
{
    $sql=" insert  into  teacher(T_Code,T_Name,T_Dept, T_Subject)  values(1,'Shailesh','IT','Programming' )";
    $result = $db->query($sql);
	 if( $result!=0)
	 {
		 echo "Inserted Sucessfully";
	 }
	 else
	 {		 echo "......not Inserted ";
	 }
	 $db->close()
}
else
{
echo 'The connection to the database could not be established.';
}
?>



2. insert row :  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 Sucessfully";
    
  $sql=" insert  into  teacher(T_Code,T_Name,T_Dept, T_Subject)  values(1,'Shailesh','IT','Programming' )"; 
  $flag=mysqli_query($db,$sql);
  echo $flag;
   if( $flag!=0)
	 {
		 echo "Inserted Sucessfully";
	 }
	 else
	 {		 echo "Not Inserted ...";
	 }
	mysqli_close($db)	;
}
?>

3. insert row : 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);
     
 $sql=" insert  into  teacher(T_Code,T_Name,T_Dept, T_Subject)  values(1,'Shailesh','IT','Programming' )";

echo " connection established  sucessfully...";
		$count=$db->exec($sql);
		if($count!=0)
		{
			echo " Inserted Sucessfully";
		}
		else
		{
			echo "....Not  inserted ";
		}
$db->close();

}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

4. MySQL Database

12may_1

 5. Table (Teacher) after  new row..

12may_2

Posted in PHP