Take the 2-minute tour ×

I'm just editing my search script after reading up on SQL injection attacks. I'm trying to get the same functionality out of my script using PDO instead of a regular mysql connection. So I've been reading other posts about PDO but am unsure. Will these two scripts give the same functionality?

With PDO:

$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);

With regular mysql:

$dbhost = @mysql_connect($host, $user, $pass) or die('Unable to connect to server');

@mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);

$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";

echo 'Your search was invalid';
} //line 18

$result = mysql_query($trim);
$numrows = mysql_num_rows($result);

I go on with the regular example to use

while($i < $numrows){
$row = mysql_fetch_array($result);

to create an array of matching results from the database. How do I do this with PDO?

share|improve this question
How does the mysql_* version work at all? You're using $query before you are declaring it... –  deceze Jun 6 '12 at 9:46
The "regular" code won't work. You set $query after you set $sql. –  Polynomial Jun 6 '12 at 9:47
possible duplicate of How can I properly use a PDO object for a Select query –  Polynomial Jun 6 '12 at 9:48
ah yeah it works and ive tested it, i just mucked it up copying it to use on here, but on my real script its all in order –  Bundy Jun 6 '12 at 9:49
I've edited the title of your question, since it had little to do with the real question, and was therefore misleading. Normally I'd cast a downvote for duplicate questions like this, but I'm refraining from doing so since it's very rare to see someone actually take our advice and use parameterised queries! –  Polynomial Jun 6 '12 at 9:56

1 Answer 1

up vote 15 down vote accepted

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();


    [0] => Array
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green

    [1] => Array
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink

share|improve this answer

Your Answer


