【问题标题】:Get query back from PDO prepared statement [duplicate]从 PDO 准备好的语句中获取查询 [重复]
【发布时间】:2011-01-15 15:16:51
【问题描述】:

有没有办法检索用于生成 PDO 准备语句对象的查询?

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    实现你想要的最简单的方法是:

    $statement->debugDumpParams();
    

    只需确保在执行语句后添加它即可。

    【讨论】:

    • 这个答案应该是最受支持/接受的。网上有很多答案,比如扩展 PDO 等,但这个是更简单快捷的答案
    【解决方案2】:

    此程序有效。由于 debugDumpParams() 不返回输出。这是我设计的一个小技巧。

    // get the output before debugDumpParams() get executed 
    $before = ob_get_contents();
    
    //start a new buffer
    ob_start();
    
    // dump params now
    $smt->debugDumpParams();
    
    // save the output in a new variable $data
    $data = ob_get_contents();
    
    // clean the output screen
    ob_end_clean();
    
    // display what was before debugDumpParams() got executed
    printf("%s", $before);
    
    $statement = "";
    
    // Now for prepared statements
    if (stristr($data, 'Sent SQL') !== false)
    {
    
    // begin extracting from "Sent SQL"
    $begin = stristr($data, 'Sent SQL');
    
    // get the first ] square bracket
    $square = strpos($begin, "]");
    
    // collect sql
    $begin = substr($begin, $square + 1);
    $ending = strpos($begin, "Params");
    
    $sql = substr($begin, 0, $ending);
    $sql = trim($sql);
    
      // sql statement here
      $statement = $sql;
    }
    else
    {
      if (stristr($data, 'SQL') !== false)
      {
         $begin = stristr($data, 'SQL');
         // get the first ] square bracket
         $square = strpos($begin, "]");
    
         // collect sql
         $begin = substr($begin, $square + 1);
         $ending = strpos($begin, "Params");
    
         $sql = substr($begin, 0, $ending);
         $sql = trim($sql);
    
         $statement = $sql;
      }
    
    }
    
    
    // statement here
    echo $statement;
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      如果您不反对扩展默认的 \PDO 和 \PDOStatement 对象,您可以考虑查看:

      github.com/noahheck/E_PDOStatement

      此 PDO 扩展允许您查看完整的查询语句作为可能在数据库级别执行的示例。它使用正则表达式来插入 PDO 语句的绑定参数。

      通过扩展默认的 \PDOStatement 定义,E_PDOStatement 能够为默认功能提供这种增强,而无需修改您的正常工作流程。

      免责声明:我创建了这个扩展。

      我只是希望它对其他人有所帮助。

      【讨论】:

        【解决方案4】:

        【讨论】:

        猜你喜欢
        • 2012-10-05
        • 1970-01-01
        • 2016-09-11
        • 2010-09-17
        • 1970-01-01
        相关资源
        最近更新 更多