PDO execute with parameter array failing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
druidmatrix
Forum Newbie
Posts: 3
Joined: Tue Jan 05, 2010 1:03 pm

PDO execute with parameter array failing

Post 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!
druidmatrix
Forum Newbie
Posts: 3
Joined: Tue Jan 05, 2010 1:03 pm

Re: PDO execute with parameter array failing

Post 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=?";
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: PDO execute with parameter array failing

Post 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 = ?";
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply