我有一个数据库存储用户根据日期添加的读数,我想根据最近添加的内容在我的HTML页面上显示读数,所以我修改了我的语句,如下所示:
public function getElecReadings(){
try {
$stmt = $this->dbconn->prepare("SELECT ElecReadingID, ElecUsage, DateAdded FROM elec_readings ORDER BY DESC WHERE AccountNumber = '" . $_SESSION['user_session'] . "'");
$stmt->execute();
return $stmt;
} catch (Exception $e) {
}
}
但是,一旦我添加ORDER BY
子句,我似乎在我的HTML页面上出现Warning: Invalid argument supplied for foreach()
错误,我在其中回显了值,
<?php
foreach ($elec_readings as $elec_reading): ?>
<tbody>
<tr>
<td><?php echo $elec_reading['ElecUsage']; ?></td>
<td><?php echo $elec_reading['DateAdded']; ?></td>
</tr>
?php
endforeach;
?>
知道为什么会这样吗?
答案 0 :(得分:2)
是。你的SQL查询现在很糟糕。订单BY是在何处关闭
(SELECT ElecReadingID, ElecUsage, DateAdded FROM elec_readings WHERE [your_condition] ORDER BY [Your_Field] DESC|ASC ");
Foreach显示错误导致SQL查询失败,$elec_readings
为空(或FALSE)
答案 1 :(得分:1)
试试这样:
public function getElecReadings(){
try {
$stmt = $this->dbconn->prepare("SELECT ElecReadingID, ElecUsage, DateAdded FROM elec_readings WHERE AccountNumber = '" . $_SESSION['user_session'] . "' ORDER BY DESC");
$stmt->execute();
return $stmt;
} catch (Exception $e) {
}
}
<?php
if (!empty($elec_readings)):
foreach ($elec_readings as $elec_reading): ?>
<tbody>
<tr>
<td><?php echo $elec_reading['ElecUsage']; ?></td>
<td><?php echo $elec_reading['DateAdded']; ?></td>
</tr>
?php
endforeach;
endif;
?>
答案 2 :(得分:1)
您收到Warning
因为您的查询无效,如果您想要使用ORDER BY和WHERE子句而不是您需要遵循此序列:
SELECT .. FROM .. WHERE .. ORDER BY ..
修改后的查询:
$stmt = $this->dbconn->prepare("
SELECT ElecReadingID, ElecUsage, DateAdded
FROM elec_readings
WHERE AccountNumber = '" . $_SESSION['user_session'] . "'
ORDER BY ElecReadingID DESC");
请注意,您还需要指定更改订单所需的列,例如,我在ElecReadingID
中使用ORDER BY DESC
列