Sunday, 12 August 2012

PDO Prepared Statements with Parameters


A query intended for use as a prepared statement looks a bit different from those you might be used
to because placeholders must be used instead of actual column values for those that will change across
execution iterations. Two syntax variations are supported, named parameters and question mark
parameters. For example, a query using named parameters might look like this:

INSERT INTO products SET sku = :sku, name = :name;

The same query using question mark parameters would look like this:

INSERT INTO products SET sku = ?, name = ?;


 I will show you how to work with both.....

To bind the values to their respective variable name or positional offset in the query using the bindParam() method.

Here is the database connection file : 

db.inc.php 

<?php
try{
$db=new PDO("mysql:host=host_name;dbname=Database_name","Your_name","Password");
}
catch(PDOException $exception)
{
    printf("Connection Error..");
}
?>


Question mark parameters :
 
<?php
include_once("db.inc.php");
$query="insert into logins set username=? , pswd=?";
//
//Insert statement
//
$stmt=$db->prepare($query);
$name="HHH";
$pswd="123";
//binding parameter
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$pswd);
$i=$stmt->execute();
if($i >0)
{
    echo "Value inserted";
}
else
{
    echo "Not Inserted";
}
?>


Name parameters :

<?php
include_once("db.inc.php");
$query="insert into logins set username=:user,pswd=:pswd";
//
//Insert statement
//
$stmt=$db->prepare($query);
$name="John";
$pswd="123";
//bind the parameter
$stmt->bindParam(':user',$name);
$stmt->bindParam(':pswd',$pswd);
//execute the query
$i=$stmt->execute();
if($i >0)
{
    echo "Value inserted";
}
else
{
    echo "Vlaue Not inserted";
}
?>

No comments:

Post a Comment