【问题标题】:Catchable fatal error: Object of class PDOStatement could not be converted to string可捕获的致命错误:PDOStatement 类的对象无法转换为字符串
【发布时间】:2012-06-02 12:36:39
【问题描述】:

尝试将数据库中的值与表单中传递的值进行匹配以检查用户是否存在时,出现以下错误。

可捕获的致命错误:不能是 PDOStatement 类的对象 转成字符串

这是我正在使用的代码:

//Check users login details
    function match_login($username, $password){
            //If the button has been clicked get the variables
            try{

                $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");

            } catch( PDOException $e ) {

                echo $e->getMessage();

            }
            $stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=? AND password=?");
            $stmt->bindParam(1, $username);
            $stmt->bindParam(2, $password);
            $stmt->execute();

            $result = mysql_query($stmt);
            if( mysql_num_rows($result) > 0 ){

                echo 'There is a match!';
            }else{
                echo 'nooooo';
            }
    }

【问题讨论】:

  • 如果您正在使用 PDO,您不应该使用 mysql_*........

标签: php mysql pdo


【解决方案1】:

mysql_query() 和 PDO 不兼容,不能一起使用。您正在尝试将 PDO 语句对象传递给需要字符串的 mysql_query()。相反,您想通过 PDO 的一种获取方法从 $stmt 获取行,或者检查使用 rowCount() 返回的行数:

$stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=? AND password=?");
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);

if ($stmt->execute()) {

  // get the rowcount
  $numrows = $stmt->rowCount();
  if ($numrows > 0) {
    // match
    // Fetch rows
    $rowset = $stmt->fetchAll();
  }
  else {
    // no rows
  }
}

【讨论】:

  • 谢谢你为什么将execute方法放在if语句中?
  • @crm 如果由于某种原因失败,它将返回 FALSE,因此只需进行简单的错误检查。我想在这种情况下,如果 execute() 失败,它会抛出异常,所以你真的不需要将它包装在 if 中。你可以把它放在 try/catch 中。
【解决方案2】:

MySQL 和 PHP5/PDO 不能很好地返回行数。在你的新 PDO() 之后,发出:

$dbh->setAttribute(PDO::MYSQL_ATTR_FOUND_ROWS, true);   

然后发出您的查询...

$stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=? AND password=?");
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);
$stmt->execute();

// number of rows returned
if($stmt->rowCount()){
    // ... matches
}else{
    // .. no match
}

否则您的 rowCount 将是 bool 0 或 null/throw 错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2013-08-07
    • 2018-03-12
    • 2014-02-21
    相关资源
    最近更新 更多