我的功能看起来像那样。
private function generateTree($courseID) {
$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
$stmt = $this->db->prepare($q);
$stmt->bind_param("i", $courseID);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $lName, $cName);
echo "<li> <a href='#'>$cName</a> <ul>";
while ($stmt->fetch()) <====HERE!!!
echo "<li> <a href='?course=$courseID&lesson=$id'> $lName </a></li>";
echo "</ul> </li>";
}
}
问题是我开始在while条件下获取数据,但是我也需要它。我可以两次获取数据吗?还有其他建议吗?
答案 0 :(得分:4)
已经四年了,但万一有人偶然发现了这个问题:
while ($stmt->fetch()) {
// do your thing
}
$stmt->data_seek(0);
while ($stmt->fetch()) {
// do something other
}
答案 1 :(得分:3)
您可以使用fetchAll()获取所有数据,并根据需要多次迭代。
$result = $stmt->fetchAll(); // PDO
$result = $stmt->fetch_all(); // MySQLi
foreach($result as $row) { print $row['lesson_name']; }
foreach($result as $row) { print $row['lesson_name']; }
foreach($result as $row) { print $row['lesson_name']; }
etc...
更新:我不完全确定你在做什么,因为你似乎有几个想法混合到你的代码中。也许你想要这样的东西?
$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
$stmt = $this->db->prepare($q);
$stmt->bind_param("i", $courseID);
$stmt->execute();
if ($stmt->num_rows > 0)
{
$results = $stmt->fetch_all();
foreach($results as $row)
{
print_r($row);
}
}
答案 2 :(得分:2)
我认为您可以以返回数据库结果数组的方式创建数据库查询类。您可以多次使用数据。
您可以像这样创建数据库结果集的数组:
while($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}