php - 在 PHP PDO 中获取最后执行的查询

标签 php pdo

我想知道使用 PHP PDO 执行什么查询。我有:

<?php

try {  
  $DBH = new PDO("mysql:host=localhost;dbname=mytable", 'myuser', 'mypass');  
}  
catch(PDOException $e) {  
    echo $e->getMessage();  
}  

$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );  
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  

$STH = $DBH->("INSERT INTO mytable (column1, column2, column3 /* etc...*/) value (:column1, :column2, :column3 /* etc...*/)"); 
$STH->bindParam(':column1', $column1);  
$STH->bindParam(':column2', $column2);  
$STH->bindParam(':column3', $column3);  
 /* etc...*/

$STH->execute();  

// what is my query?

我想得到这样的东西:

INSERT INTO mytable (column1, column2, column3) value ('my first column', 32, 'some text')

这可能吗?谢谢

最佳答案

<?php

class MyPDOStatement extends PDOStatement
{
  protected $_debugValues = null;

  protected function __construct()
  {
    // need this empty construct()!
  }

  public function execute($values=array())
  {
    $this->_debugValues = $values;
    try {
      $t = parent::execute($values);
      // maybe do some logging here?
    } catch (PDOException $e) {
      // maybe do some logging here?
      throw $e;
    }

    return $t;
  }

  public function _debugQuery($replaced=true)
  {
    $q = $this->queryString;

    if (!$replaced) {
      return $q;
    }

    return preg_replace_callback('/:([0-9a-z_]+)/i', array($this, '_debugReplace'), $q);
  }

  protected function _debugReplace($m)
  {
    $v = $this->_debugValues[$m[1]];
    if ($v === null) {
      return "NULL";
    }
    if (!is_numeric($v)) {
      $v = str_replace("'", "''", $v);
    }

    return "'". $v ."'";
  }
}

// have a look at http://www.php.net/manual/en/pdo.constants.php
$options = array(
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_STATEMENT_CLASS => array('MyPDOStatement', array()),
);

// create PDO with custom PDOStatement class
$pdo = new PDO($dsn, $username, $password, $options);

// prepare a query
$query = $pdo->prepare("INSERT INTO mytable (column1, column2, column3)
  VALUES (:col1, :col2, :col3)");

// execute the prepared statement
$query->execute(array(
  'col1' => "hello world",
  'col2' => 47.11,
  'col3' => null,
));

// output the query and the query with values inserted
var_dump( $query->queryString, $query->_debugQuery() );

关于php - 在 PHP PDO 中获取最后执行的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7716785/

相关文章:

php - 在 WooCommerce 单一产品页面中添加 OpenGraph 标签

php - OAUTH 使用 PHP 的 PECL OAUTH - 使用方法 getRequestToken() 时不能使用 POST?

php - 为什么这个 PDO 语句会默默地失败?

php - GAE SQLSTATE 上的 PDO[HY000] [2002]

php artisan 迁移: PDOException could not find driver

php - PDO - 具有数组方面的 Foreach

PHP 防止 session 固定/劫持

php - 如何处理含有非法字符的XML

php - 使用 magento 安全 url 进行操作时,表单提交不起作用

php - MYSQL字段ID值变化