In this tutorial we will study about PDO Prepared Statement in PHP, how to access MySQL using PDO Prepared Statement , How to retrieve data etc. Examples will make this clearer.
In this tutorial we will study about PDO Prepared Statement in PHP, how to access MySQL using PDO Prepared Statement , How to retrieve data etc. Examples will make this clearer.PDO Prepared Statements:
In this current tutorial we will study about prepared statements and how to use it using PDO.
Sometimes it is more commodious for us to use a Prepared Statement for
sending SQL statements to the database. It is beneficial when we need to execute
an SQL statement more than one time, using this we can reduce the execution
time.
The prepared statement can be considered as a kind of precompiled template which
can be run by an application and the parameters are custmizable. Prepared
statements offer the following benefits:
Example:
<?php
$host='localhost';
$user='root';
$db='ajax';
$password='';
try
{
$dbh=new PDO("mysql:host=$host;dbname=$db",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$f_name='sachin';
$l_name='Gambhir';
$e_city='new delhi';
$stmt=$dbh->prepare("select * from emp_details where emp_first_name=:f_name");
$stmt->bindParam(':f_name',$f_name,PDO::PARAM_STR,10);
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row)
{
echo $row['emp_first_name']."<br/>";
echo $row['emp_last_name']."<br/>";
echo $row['emp_city']."<br/>";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Output:
sachin
tendulkar
mumbai