tournasdim
6/25/2013 - 5:05 AM

PDO prepared statement example (with/without POST-data)

PDO prepared statement example (with/without POST-data)

<?php

// PDO without prepared statement
$connStr = 'mysql:host=localhost;dbname=world' ; 
try
{
$conn = new PDO($connStr, 'root', '');
}
catch(PDOException $pe)
{
echo '<pre>' ; 
print_r($pe)  ; 
die('Could not connect to the database because: ' . $pe->getMessage() ) ;
}

$q = $conn->query("SELECT * FROM city Limit 5") ;
if(!$q) {
$ei = $conn->errorInfo();
die('Could not execute query because: ' . $ei[2]) ;
}
foreach($q as $r=>$v)
{
echo '<pre>' ; 
print_r($v)  ;
 echo $r , $v[1] , '<br>' ;
}

// Using PDO with Prepared statements 
echo '<h3>Prepared Statements </h3>'  ; 
$dsn = 'mysql:dbname=world;host=127.0.0.1';
try {
     $db = new PDO($dsn , 'root' , '');
}
catch(PDOException $e) {
     echo $e->getMessage();
}
$query = 'SELECT * FROM  city WHERE Name = ?' ;
$statement = $db->prepare($query);
$statement->execute(array('Eindhoven')) ;
$rows = $statement->fetchAll(PDO::FETCH_NUM) ;
echo '<pre>'  ;
print_r($rows)  ;
foreach($rows as $row)
{
     echo $row[3] , '<br>' ;
}




// Using POST values and Mysql-driver 
mysql_connect('localhost', 'user', 'password');
mysql_select_db('myDB');

$data = mysql_real_escape_string($_POST['data']);
$query = 'SELECT column FROM table WHERE data = \'' . $data . '\'';

$result = mysql_query($query);
while($row = mysql_fetch_array($result, FETCH_NUM))
{
     echo $row[0];
}



// Using POST values and PDO-driver (using prepared statements)
$dsn = 'mysql:dbname=myDB;host=127.0.0.1';
try {
     $db = new PDO($dsn , 'user' , 'password');
}
catch(PDOException $e) {
     echo $e->getMessage();
}

$query = 'SELECT column FROM table WHERE data = ?';
$statement = $db->prepare($query);
$statement->bindParam(1 , $_POST['data']);
$statement->execute();

$rows = $statement->fetchAll(PDO::FETCH_NUM);

foreach($rows as $row)
{
     echo $row[0];
}