2012-06-02 64 views
6

嘗試將數據庫中的值與表單中傳遞的值進行匹配以檢查用戶是否存在時,出現以下錯誤。可捕捉的致命錯誤:PDoCtatement類的對象無法轉換爲字符串

Catchable fatal error: Object of class PDOStatement could not be converted to string

這是我使用的代碼:

//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'; 
      } 
    } 
+3

如果你正在使用PDO,你不應該使用'mysql_ *'........ – Esailija

回答

7

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 
    } 
} 
+0

謝謝你爲什麼將執行方法放在if語句中? – crm

+1

@crm如果由於某種原因失敗,它將返回FALSE,所以只需簡單的錯誤檢查。我想在這種情況下,如果execute()失敗,它會拋出一個異常,所以你並不需要將它封裝在if中。你可以把它放在try/catch中。 –

+0

好的,謝謝邁克爾。 – crm

1

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,或空/拋出錯誤。

相關問題