2012-03-01 54 views
6

我遇到了PDO準備好的語句和rowCount返回錯誤的受影響行數的問題。PDO rowCount無法返回受影響的行的正確數量

我有一個簡單的測試數據庫:

create table test (
    boolean var1; 
); 

然後,我有以下的測試代碼:

$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)"); 
$sth->execute(array(':val' => true)); 
echo $sth->rowCount(); 

預期將返回:1行受到影響

當我插入插入失敗:

$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)"); 
$sth->execute(array(':val' => 20)); 
echo $sth->rowCount(); 

它返回預期:0行受到影響

然而,當我有多個插入 - 在

$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)"); 

$sth->execute(array(':val' => true)); 
echo $sth->rowCount() . ", "; 

$sth->execute(array(':val' => 20)); 
echo $sth->rowCount(); 

結果:1,1

如果我翻轉執行順序,我得到:0,1

爲什麼rowCount() - 受影響的行在失敗語句後未成功設置爲零ss聲明?

我運行PHP 5.3.6-13和PostgreSQL 9.1

+1

只要開啓了PDO的例外,並得到一個更好的辦法處理這種情況 – zerkms 2012-03-01 01:27:06

+1

這對我來說很合理,因爲您重新使用了相同的PDO。如果您需要爲每個語句分別設置一個rowCount,則準備第二個語句。 – Ozzy 2012-04-27 11:28:48

回答

2

在我看來,那$sth->execute(array(':val' => true))成功完成,從而增加了rowCount,但$sth->execute(array(':val' => 20))沒有。這裏是rowCount$sth每個階段的狀態:

$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)"); 

# No successful DML queries have been done with the $sth yet. 
# rowCount == 0 

$sth->execute(array(':val' => true)); 
echo $sth->rowCount() . ", "; 

# rowCount increases because of a successful INSERT statement 
# rowCount == 1 

$sth->execute(array(':val' => 20)); 
echo $sth->rowCount(); 

# rowCount does not increase due to failed INSERT statement 
# rowCount == 1 

現在,讓我們來看看,在相反的順序:

$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)"); 

# No successful DML queries have been done with the $sth yet. 
# rowCount == 0 

$sth->execute(array(':val' => 20)); 
echo $sth->rowCount(); 

# rowCount does not increase due to failed INSERT statement 
# rowCount == 0 

$sth->execute(array(':val' => true)); 
echo $sth->rowCount() . ", "; 

# rowCount increases because of a successful INSERT statement 
# rowCount == 1 
相關問題