0

I've written a function that should replace ?'s with values from an array, but I can't get it to work.

 public function exec($sql, Array $params = array()) {
            if($query = $this->db->prepare($sql)) {
                    $x = 1;
                    if(count($params)) {
                            foreach($params as $param) {
                                    $query->bindParam($x, $param);
                                    $x++;
                            }
                    }
            }
            $query->execute();
            print_r($query);

Query:

$mysql->exec("SELECT * FROM test where id = ?", array(0));

Output:

PDOStatement Object ( [queryString] => SELECT * FROM test where id = ? )
ethan476
  • 11
  • 2
  • What error do you get? – vallentin Oct 16 '13 at 03:27
  • No error, but the ? isn't replaced. – ethan476 Oct 16 '13 at 03:28
  • 1
    `print_r($query);` will not work as the bound query does not exist in php as the query/params are sent seperately to mysql. see http://stackoverflow.com/questions/210564 OR http://stackoverflow.com/questions/1786322 OR http://stackoverflow.com/questions/11122573 OR http://stackoverflow.com/questions/530627-it/530705#530705. You could use [`print_r($query->debugDumpParams());`](http://php.net/manual/en/pdostatement.debugdumpparams.php) – Sean Oct 16 '13 at 03:45
  • Why not skip your convoluted binding process and simply use `$query->execute($params)`? – Phil Oct 16 '13 at 04:39

2 Answers2

1

Everything works fine, the reason you still see the ? while calling print_r($query); is because the values never actually gets put into the query itself.

The way prepared statements work, is that when you call prepare() then the query is sent to the database. Then when you later call execute() then all the values are sent to the database, and it will do the rest of the work.

Basically you're query and the value never ever gets connected or put together, that is also why you don't have to escape the values.

vallentin
  • 23,478
  • 6
  • 59
  • 81
-1

try

$result = $query->fetchAll();
print_r($result);

instead of

print_r($query);
Pramod
  • 29
  • 3