Skip to content

Instantly share code, notes, and snippets.

@tournasdim
Created June 25, 2013 04:35
Show Gist options
  • Save tournasdim/5855962 to your computer and use it in GitHub Desktop.
Save tournasdim/5855962 to your computer and use it in GitHub Desktop.
PDO with prepare statement example
<?php
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];
}
//Now with PDO
$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