Page 1 of 1

PDO execute with parameter array failing

Posted: Tue Jan 05, 2010 1:07 pm
by druidmatrix
I am having a strange problem using PDO with parameters being passed in - the execute fails with the following errorInfo:

<?php

Code: Select all

 
        $query = "select user_id from USERS where username='?'";
        $params = array('root');
 
        try {
                $pdo = new PDO('mysql:host=localhost;dbname=dbname', 'db_user', 'db_pass');
        }
        catch (PDOException $e) {
                die ('PDO Connect Error (' . $e->getMessage() . ') '. "\n");
        }
 
        $stmt = $pdo->prepare($query);
        if (!$stmt)
                echo "Failed to prepare statement: (". print_r($pdo->errorInfo()).")\n";
 
        $stmt->execute($params);
        echo "Issueing SQL prepared statement\n";
        $stmt->debugDumpParams()."\n";
        if ($stmt->errorCode()) {
                echo "Failed to execute statement: \n=======\n";
                $arr = $stmt->errorInfo();
                print_r($arr);
                echo "\n========\n";
        }
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
                        echo "Query Result: ".print_r($row)."\n";
        else
                echo "Query failed\n";
 
?>
And the run results:
Issueing SQL prepared statement
SQL: [44] select user_id from USERS where username='?'
Params: 1
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=2
Failed to execute statement:
=======
Array
(
[0] => 00000
)

========
Query failed
I am new to PHP and would be grateful for any help from the experts out there!

Re: PDO execute with parameter array failing

Posted: Tue Jan 05, 2010 3:22 pm
by druidmatrix
For anybody interested, the issue was resolved in a different forum.

Problem with the above code was the single quotes around the anonymous placeholder (?). The correct query string should have been:

Code: Select all

$query = "select user_id from USERS where username=?";

Re: PDO execute with parameter array failing

Posted: Tue Jan 05, 2010 3:26 pm
by AbraCadaver
Doh! Beat me to it.

I think prepare() will quote strings for you. So try this instead:

Code: Select all

$query = "select user_id from USERS where username = ?";