Skip to content

Instantly share code, notes, and snippets.

@tournasdim
Created June 25, 2013 05:05
Show Gist options
  • Save tournasdim/5856059 to your computer and use it in GitHub Desktop.
Save tournasdim/5856059 to your computer and use it in GitHub Desktop.
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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment