我想从数据库中获取一行并显示在我的页面中。以下代码无效,我的浏览器挂起。而且我不知道如何解决。请帮助我。
班级
public function get_calculate($id)
{
if ($id != 0) {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.id=:calculate_id AND analix_calculate.is_active=1;');
$stmt_select_calculate->bindValue(':calculate_id', $id, PDO::PARAM_STR);
} else {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.is_active=1;');
}
return $stmt_select_calculate->execute();
}
index.php:
<?php
include("../db/Database.php");
$databse = new Database();
$menu = $databse->get_calculate(0);
while ($row_select_calculate = $menu) {
?>
<li>
<a href="#0">
<i class="fa fa-home" aria-hidden="true"></i><?php echo $row_select_calculate['title']?>
</a>
</li>
<?php
}
?>
答案 0 :(得分:1)
首先,$stmt_select_calculate->execute();
returns布尔值。很明显,您不能迭代布尔值。因此,您应该返回语句对象本身:
public function get_calculate($id)
{
if ($id != 0) {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.id=:calculate_id AND analix_calculate.is_active=1;');
$stmt_select_calculate->bindValue(':calculate_id', $id, PDO::PARAM_STR);
} else {
$stmt_select_calculate = $this->connect()->prepare('SELECT analix_calculate.title,analix_calculate.basis FROM analix_calculate where analix_calculate.is_active=1;');
}
$stmt_select_calculate->execute();
return $stmt_select_calculate;
}
在index.php
中,您应该fetch
数据:
$menu_stmt = $databse->get_calculate(0);
while ($row = $menu_stmt->fetch()) {
?>
<li>
<a href="#0">
<i class="fa fa-home" aria-hidden="true"></i><?php echo $row['title']?>
</a>
</li>
<?php
}