Search code examples
phppdoprepared-statementpear

PEAR DB prepare/bind values


Just can't seem to print the binded values without executing the query. Looking to debug the query before execution. Any tips? I know I'm overlooking something simple, ugh...

$field1 = 'one';
$field2 = 'two';
$field3 = 'three';

$fields  = 'SET ';
$fields .= 'field1 = ?, ';
$fields .= 'field2 = ?, ';
$fields .= 'field3 = ? ';

$vals[] = $field1;
$vals[] = $field2;
$vals[] = $field3;

$sql = 'UPDATE table_name '.$fields.' WHERE id = 123';
$dbh = $db->prepare($sql);

// this binds and executes the query but I would like to print the query with the bind values before executing
$results = $db->execute($dbh, $vals); 

UPDATE:

I would do something like this with sprinf

$field1 = 'one';
$field2 = 'two';
$field3 = 'three';

$fields  = 'SET ';
$fields .= 'field1 = %s, ';
$fields .= 'field2 = %s, ';
$fields .= 'field3 = %s ';

$vals[] = $field1;
$vals[] = $field2;
$vals[] = $field3;

$sql = 'UPDATE table_name '.$fields.' WHERE id = 123';

$query = sprintf($sql, $field1, $field2, $field3);
echo "Query before execution: ".$query."<br />";

Solution

  • You can't get the values inside the query like that. The way the server handles prepared queries is different.

    The best you could do is:

    echo $sql;
    print_r($vals);
    

    Retrieve (or simulate) full query from PDO prepared statement