$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if (it is 1st record){
echo "make orange juice";
}else{
echo "make all juice";
}
}
假设输出是来自数据库“Zac”、“Michelle”、Andrew”的 3 条记录。“Zac”是从数据库获取的第一条记录,如何编写“if”语句来检查记录是否是第一条记录?
首先,如果返回的记录顺序很重要,则必须明确包含ORDER BY
查询中的子句指定对结果进行排序的列。否则,返回的行的顺序在技术上是不确定的。
要对第一个获取的行与后续行进行不同的操作,您可以简单地调用fetch()
首先在循环之外,然后循环剩余部分。每次致电PDOStatement::fetch()
将推进行集记录指针,因此while
循环只会迭代已检索的记录之后的记录。
// Fetch the first row from the rowset
$r3 = $q3->fetch(PDO::FETCH_ASSOC);
$level3downlines = $r3['member'];
// Do actions specific to 1st row before the loop
echo "make orange juice";
// Then fetch the remaining rows with a loop
// and perform the their actions in the loop.
// The rowset record pointer has advanced beyond the 1st row
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
echo "make all juice";
}
在实践中,除非行集非常大,否则我不经常在获取行时进行操作。相反,我更有可能将所有行作为数组检索,这样我可以更轻松地在集合上执行数组操作。
// Get all rows
$all_rows = $q3->fetchAll(PDO::FETCH_ASSOC);
// Pull the first row off the set
$first_row = array_shift($all_rows);
// do whatever with $first_row
// Loop over the other rows
foreach ($all_rows as $index => $row) {
// Do whatever with $row
}
而不是使用array_shift()
这样,当使用$index => $row
in the foreach
循环,你也可以检查$index == 0
对您的第一行进行操作。您可能会发现这更容易理解。
foreach ($q3->fetchAll(PDO::FETCH_ASSOC) as $index => $row) {
// First row
if ($index == 0) {
// Do first row actions
}
else {
// Do common actions for remaining rows.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)