問題描述
我正在嘗試將一些數據添加到我的數據庫中,但我收到錯誤 Catchable fatal error: Object of class PDOStatement could not be convert to string in/var/www/mandje.php 第 114 行.這是我正在使用的代碼:
I'm trying to add some data to my database, but I'm getting the error Catchable fatal error: Object of class PDOStatement could not be converted to string in /var/www/mandje.php on line 114. This is the code I'm using:
foreach($_SESSION["cart"] as $id => $value){
$query = $db->query('SELECT * FROM Producten WHERE ProductID ="'.$id.'" ');
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$price = $row['Prijs'];
$ProductID = $row['ProductID'];
}
$sql="INSERT INTO Bestellingsdetail( Bestelnummer, ProductID, Aantal, Prijs)
VALUES ($max,$ProductID,$value,$price)"; //<---- line 114
$count = $db->execute($sql);
我真的不明白這里出了什么問題.任何幫助將不勝感激:)
I don't really get what's going wrong here. Any help would be much appreciated :)
推薦答案
在評論中,您顯示以下內容:
In the comments, you show the following:
$query = $db->query('SELECT MAX( Bestelnummer ) FROM Bestellingsdetail');
$query->execute();
$max = $query;
$max++;
這不是您從查詢中獲得結果的方式.您正在將 $max
設置為 PDOStatement
對象.您需要 fetch()
結果才能使用它.
This is not how you get the result from a query. You are setting $max
to a PDOStatement
object. You need to fetch()
the result in order to use it.
// I've added "AS maxval" to make it easier to get the row
$query = $db->query('SELECT MAX(Bestelnummer) AS maxval FROM Bestellingsdetail');
$max_row = $query->fetch(PDO::FETCH_ASSOC);
$max = $max_row['maxval'];
$max++;
文檔:http://www.php.net/pdo.query
附言$query->execute();
只有準備好的語句才需要.query()
將立即執行查詢.
P.S. $query->execute();
is only needed for prepared statements. query()
will execute the query immediately.
這篇關于可捕獲的致命錯誤:無法在第 114 行將類 PDOStatement 的對象轉換為字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!