Getting raw SQL query string from PDO prepared statements

前端 未结 16 1151
心在旅途
心在旅途 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 07:04

    A solution is to voluntarily put an error in the query and to print the error's message:

    //Connection to the database
    $co = new PDO('mysql:dbname=myDB;host=localhost','root','');
    //We allow to print the errors whenever there is one
    $co->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    //We create our prepared statement
    $stmt = $co->prepare("ELECT * FROM Person WHERE age=:age"); //I removed the 'S' of 'SELECT'
    $stmt->bindValue(':age','18',PDO::PARAM_STR);
    try {
        $stmt->execute();
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
    

    Standard output:

    SQLSTATE[42000]: Syntax error or access violation: [...] near 'ELECT * FROM Person WHERE age=18' at line 1

    It is important to note that it only prints the first 80 characters of the query.

提交回复
热议问题