代码之家  ›  专栏  ›  技术社区  ›  JD Isaacks

PDO错误信息?[副本]

  •  35
  • JD Isaacks  · 技术社区  · 15 年前

    这个问题已经有了答案:

    以下是我的代码片段:

    $qry = '
        INSERT INTO non-existant-table (id, score) 
        SELECT id, 40 
        FROM another-non-existant-table
        WHERE description LIKE "%:search_string%"
        AND available = "yes"
        ON DUPLICATE KEY UPDATE score = score + 40
    ';
    $sth = $this->pdo->prepare($qry);
    $sth->execute($data);
    
    print_r($this->pdo->errorInfo());
    

    这应该会给我一个错误,因为表根本不存在。但我得到的只是:

    数组([0]=>00000)

    如何更好地描述错误,以便调试问题?

    4 回复  |  直到 7 年前
        1
  •  86
  •   Neuron MonoThreaded    7 年前

    试试这个:

    print_r($sth->errorInfo());
    

    在准备之前添加:

    $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    

    这将更改PDO错误报告类型,并使其在出现PDO错误时发出警告。它可以帮助你追踪它,尽管你的错误信息应该已经设置好了。

        2
  •  4
  •   lumonald    10 年前

    旧线索,但也许我的答案会帮助某人。我首先执行查询,然后设置一个错误变量,然后检查该错误变量数组是否为空。参见简化示例:

    $field1 = 'foo';
    $field2 = 'bar';
    
    $insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
    $insert_QUERY->bindParam(':field1', $field1);
    $insert_QUERY->bindParam(':field2', $field2);
    
    $insert_QUERY->execute();
    
    $databaseErrors = $insert_QUERY->errorInfo();
    
    if( !empty($databaseErrors) ){  
        $errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
        $errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...         
    
    /* 
     $errorLogMsg will return something like: 
     error info:  
     Array(
      [0] => 42000
      [1] => 1064
      [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES                                                  ('bar', NULL)' at line 1
     )
    */
    } else {
        # no SQL errors.
    }
    
        3
  •  3
  •   uınbɐɥs Alex Reynolds    13 年前

    也许这篇文章太老了,但它可能有助于建议周围的人看看: 而不是使用:

     print_r($this->pdo->errorInfo());
    

    使用php implode()函数:

     echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
    

    这应该打印错误代码、详细的错误信息等,如果使用某些SQL用户界面,通常会得到这些信息。

    希望有帮助

        4
  •  2
  •   thetaiko    15 年前

    从手册中:

    如果数据库服务器成功 准备语句,pdo::prepare()。 返回pPostStatement对象。如果 数据库服务器无法成功 准备语句,pdo::prepare()。 返回false或发出pdoException (取决于错误处理)。

    Prepare语句可能会导致错误,因为数据库将无法准备该语句。在准备好查询并执行查询之前,请立即尝试测试错误。

    $qry = '
        INSERT INTO non-existant-table (id, score) 
        SELECT id, 40 
        FROM another-non-existant-table
        WHERE description LIKE "%:search_string%"
        AND available = "yes"
        ON DUPLICATE KEY UPDATE score = score + 40
    ';
    $sth = $this->pdo->prepare($qry);
    print_r($this->pdo->errorInfo());