我想检查查询是否带来结果。现在,我为我的查询创建一个rowcount。如果行数是>然后0我再次创建一个新查询,获取查询的所有结果。当我在a-z的范围内创建一个alphabethic查询循环(即WHERE name LIKE "a%"
)时,它将导致52个查询完成任务,这有点过分了。你是如何面对这种任务的?结果我想渲染一个带有字母排序链接的菜单。
A
----
Apple Link
Annanas Link
B
----
Banana Link
etc.
也许还有另一种方法可以在一个查询中执行此操作并以某种方式扩展结果字母,因为我需要为每个字母呈现一个新的介绍menupoint。我希望你有一些有用的指针来调整我的表现
答案 0 :(得分:2)
您不能一次选择所有内容并按列排序吗?
SELECT * FROM your_table ORDER BY column_name ASC
然后,如果有行并且比较第一个字母以确定您所在的字母,则可以循环播放:
$stmt->execute();
if ($stmt->rowCount()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$value = $row['column_name'];
$first_letter = $value[0];
}
}
获得第一个字母后,您可以使用值
执行任何操作要扩展此答案,您可以使用类似的内容来回显带有标题的值:
// initialize this variable
$current_letter = '';
// if you get results
if ($stmt->rowCount()) {
// loop through each row
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// when you loop, get the value
$value = $row['column_name'];
// if the value does not have the current letter you are on:
if ($current_letter != $value[0]) {
// echo a header for the new letter
echo "<h2>" . $value[0] . "</h2>";
// set the new letter to the current letter
$current_letter = $value[0];
// echo the actual value
echo $value . "<br />";
} else {
// the value falls under our current letter, echo it
echo $value . "<br />";
}
}
}