Home Tutorial Php Phppdo Tutorial PDO Prepared Statement

 
 

Share on Google+Share on Google+
PDO Prepared Statement
Posted on: April 6, 2010 at 12:00 AM
Advertisement
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:

  • The only requirement in this statement is that the query should be parsed once, and that can be executed many times. The prepared statement use fewer resources and for this reason it runs faster.
  • The parameters of prepared statement need not to be quoted because the driver of SQL automatically handles this.

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

Advertisement

Related Tags for PDO Prepared Statement :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 6, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com