我希望在这篇文章中让我的生活更轻松:
PDO::bindParam in a foreach loop, all values are being set as the same?
还有其他几个......
我尝试了几种变体来让我的代码工作(看消息),但是没有结果我必须在我的班级中使用方法:
public function getMessages($locationId, $name) {
if(!empty($name)) {
$query = 'SELECT * FROM (SELECT * FROM sms WHERE location_id=:locationId ORDER BY id DESC LIMIT 5) AS SOURCE ORDER BY id ASC';
$parameters = array(':locationId' => $locationId);
$row = $this->returnDataObject($query, $parameters);
while ($row) {
$this->fetchData($row, $biggestId, $name);
}
$this->updateSessionKey($locationId, $name);
}
}
另一个:
public function returnDataObject($query, $parameters) {
var_dump($query);
var_dump($parameters);
$dataObject = $this->dbh->prepare($query);
foreach ($parameters as $key => &$value) {
$dataObject->bindParam($key, $value);
}
$dataObject->execute();
$row = $dataObject->fetch(PDO::FETCH_OBJ);
return $row;
}
我试过了:
foreach ($parameters as $key => &$value) {
and:
foreach ($parameters as $key => $value) {
我试过了:
$dataObject->bindParam($key, $value);
and:
$dataObject->bindValue($key, $value);
我也试过在getMessages方法中死掉('我在getMessages方法'); 但是我无法做到那么远......
我应该采取哪些不同的方式来使这段代码有效?
我感谢任何帮助!
编辑:
我对bigId表示不好,但声称是最大的:
$biggestId = $this->getBiggestId($locationId);
但是修复并没有解决整个问题。第一种方法如果是:
则执行public function getMessages($locationId, $name) {
if(!empty($name)) {
$biggestId = $this->getBiggestId($locationId);
$messages = $this->dbh->prepare('SELECT * FROM (SELECT * FROM sms WHERE location_id=:locationId ORDER BY id DESC LIMIT 5) AS SOURCE ORDER BY id ASC');
$messages->bindParam(':locationId', $locationId);
$messages->execute();
while ($row = $messages->fetch(PDO::FETCH_OBJ)) {
$this->fetchData($row, $biggestId, $name);
}
$_SESSION[$name] = $biggestId;
}
}
但是我想使用这个方法,所以我不必手动使用bindParam / BindValue,returnDataObject方法的功能会让我的生活更轻松......
答案 0 :(得分:2)
进行以下更改:
fetchAll()
代替fetch()
fetchAll()
后,请使用foreach
而不是while
循环。<强> returnDataObject:强>
public function returnDataObject($query, $parameters) {
$dataObject = $this->dbh->prepare($query);
foreach ($parameters as $key => &$value) {
$dataObject->bindParam($key, $value);
}
$dataObject->execute();
$rows = $dataObject->fetchAll(PDO::FETCH_OBJ);
return $rows;
}
<强>的getMessages:强>
public function getMessages($locationId, $name) {
if(!empty($name)) {
$query = 'SELECT * FROM (SELECT * FROM sms WHERE location_id=:locationId ORDER BY id DESC LIMIT 5) AS SOURCE ORDER BY id ASC';
$parameters = array(':locationId' => $locationId);
$rows = $this->returnDataObject($query, $parameters);
foreach($rows as $row) {
$this->fetchData($row, $biggestId, $name);
}
$this->updateSessionKey($locationId, $name);
}
}