Getting raw SQL query string from PDO prepared statements

前端 未结 16 1069
心在旅途
心在旅途 2020-11-22 06:56

Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.

16条回答
  •  Happy的楠姐
    2020-11-22 07:17

    You can use sprintf(str_replace('?', '"%s"', $sql), ...$params);

    Here is an example:

    function mysqli_prepared_query($link, $sql, $types='', $params=array()) {
        echo sprintf(str_replace('?', '"%s"', $sql), ...$params);
        //prepare, bind, execute
    }
    
    $link = new mysqli($server, $dbusername, $dbpassword, $database);
    $sql = "SELECT firstname, lastname FROM users WHERE userage >= ? AND favecolor = ?";
    $types = "is"; //integer and string
    $params = array(20, "Brown");
    
    if(!$qry = mysqli_prepared_query($link, $sql, $types, $params)){
        echo "Failed";
    } else {
        echo "Success";
    }
    

    Note this only works for PHP >= 5.6

提交回复
热议问题