【问题标题】:Query looks OK but I have error查询看起来不错,但我有错误
【发布时间】:2015-10-06 19:24:55
【问题描述】:

我有这个 SQL 查询

$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array('Status' => 'NotActive', 'Username' => $Username, 'Password' => $PasswordHash, 'FirstName' => $FirstName, 'LastName' => $LastName, 'EmailAddress' => $EmailAddress, 'API_Status' => 'OFF', 'API_Key' => $API_Key, 'About' => $Other));      

执行此查询时,我使用的是try {

catch(PDOException $e) {
   echo $sql . "<br>" . $e->getMessage();
}

现在当我运行脚本时,我得到了这个 PHP 错误:

可捕获的致命错误:不能是 PDOStatement 类的对象 在第 94 行的 /var/www/html/register.php 中转换为字符串

我该如何解决这个问题?

【问题讨论】:

  • 当 $sql 是一个对象时不要使用 echo $sql
  • 执行类似 echo 'INSERT INTO.........' 并在 phpmyadmin 上测试
  • 那么.../var/www/html/register.php on line 94 是哪一行?

标签: php mysql pdo


【解决方案1】:

您无法在使用时回显您的 sql,您可能需要使用 debugDumpParams() 尝试这样的操作。

$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');

$sql->execute(array(':Status' => 'NotActive', ':Username' => $Username, ':Password' => $PasswordHash, ':FirstName' => $FirstName, ':LastName' => $LastName, ':EmailAddress' => $EmailAddress, ':API_Status' => 'OFF', ':API_Key' => $API_Key, ':About' => $Other));      

echo $sql->debugDumpParams();

【讨论】:

    【解决方案2】:

    有问题的问题。

    1. 命名错误。 SQL 是传递给prepare() 的文本。虽然返回值是一个对象。问题未解决。
    2. 由于命名错误,OP 试图回显一个对象。问题未解决。
    3. 感谢 Stack Overflow 的伟大站点,教了 OP terrible wrong way of handling PDO errors,使用了无用的 try..catch 内容。问题未解决。
    4. :缺少一个占位符。唯一解决的问题。

    因此,下次此查询抛出异常时,将产生相同的完全无用和不相关的错误消息。

    应该怎么做?

    $sql = 'INSERT INTO Accounts 
        (Status, Username, Password, FirstName, LastName, EmailAddress,
         API_Status, API_Key, About) 
        VALUES (:Status, :Username, :Password, :FirstName, 
        :LastName, :EmailAddress, :API_Status, :API_Key, :About)';
    $data = array(
        'Status' => 'NotActive', 
        'Username' => $Username, 
        'Password' => $PasswordHash, 
        'FirstName' => $FirstName, 
        'LastName' => $LastName, 
        'EmailAddress' => $EmailAddress, 
        'API_Status' => 'OFF', 
        'API_Key' => $API_Key, 
        'About' => $Other
    );
    $conn->prepare($sql)->execute($data);
    

    我们这里有什么?

    • 正确命名。如果有人喜欢回显 SQL 查询,他们不会错的。
    • 可读性。屏幕上没有冗长的代码,让我们可以直观地检查查询并找到语法错​​误。
    • 更正了占位符语法。
    • 没有回显语句对象。 SQL 都不是,因为在准备好的语句的情况下它几乎没有意义。
    • 没有愚蠢的 try..catch 块。意味着 PHP 将能够在发生错误时通知 PHP 用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多