'debug sql statements - parameter values

I have this sql statment:

try {
    $sql = $db->prepare( "INSERT INTO myTable (column_a) VALUES (:value_a)" );

    $sql->execute( array( 
            ":value_a"              => $value_a
    ));
        

} catch (PDOException $e) { 
    echo $e->getMessage();
}

In the catch block, I get the sql error message. But I would like to know, which paramaters and which values were send to the database. Is there a solution for?



Solution 1:[1]

Since you're preparing your variables before the try-clause you can just dump them too in the catch.

try {
    $sql = $db->prepare( "INSERT INTO myTable (column_a) VALUES (:value_a)" );
    $sql->execute( array( 
            ":value_a" => $value_a
    ));    

} catch (PDOException $e) { 
    var_dump($e->getMessage(), $value_a);
}

Also, if you are using PHP 5.4 or higher (higher I really hope) you could/should use short syntax for arrays. It's just nicer and easier to read.

$sql->execute([":value_a" => $value_a]); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christoffer