2011-07-21 124 views
8

此:PDO通過參考通知?

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color"); 
$stmt->bindParam(':color', $someClass->getColor()); 
$stmt->execute(); 

產生這樣的:

運行時通知
只有變量應該由 參考

雖然它仍然執行傳遞。

此:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color"); 
$tempColor = $someClass->getColor(); 
$stmt->bindParam(':color',$tempColor); 
$stmt->execute(); 

運行毫無怨言。

我不明白區別?

回答

6

bindParam的第二個參數是一個變量reference。由於無法引用函數返回,因此無法嚴格滿足bindParam參數的需要(PHP將與您一起工作,並且只會在此處發出警告)。

爲了得到一個更好的主意,這裏的和示例:此代碼將產生相同的結果作爲你的第二個例子:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color"); 
$tempColor = NULL; // assigned here 
$stmt->bindParam(':color',$tempColor); 
$tempColor = $someClass->getColor(); // but reassigned here 
$stmt->execute(); 

這不會是可能的函數返回。

9

PDOStatement::bindParam()的描述聲明它將PHP 變量綁定到quesitonmark或命名的佔位符。既然你正試圖傳遞一個類的方法(即使該方法確實返回一個值),它仍然不是一個變量名,因此是警告。您可能需要查看PDOStatement::bindValue(),以確保您的代碼具有未來性。

2

如果你想避免分配值給一個變量,你可能會更好嘗試:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = ?"); 
$stmt->execute(array($someClass->getColor())); 

正如其他人所說,該錯誤造成的,因爲PDO::statement->bindParam預計參數2要由一個變量傳遞參考。

-1

如果你真的想綁定一個值,而不是一個參考,你可以使用PDOStatement::bindValue,然後你的代碼會是這個樣子:

$stmt = $dbh->prepare("SELECT thing FROM table WHERE color = :color"); 
$stmt->bindValue('color', $someObject->getColor()); 
$stmt->execute();