$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“是从数据库获取的第1条记录,如何编写”if“语句来检查记录是第1条记录还是不?
答案 0 :(得分:2)
首先,如果返回的记录顺序很重要,则必须在查询中明确包含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
循环中使用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.
}
}
答案 1 :(得分:1)
我不确定我是否理解你,但你想为第一行做一个特别的动作,
$sql3 = "SELECT member FROM levels where upline = ? AND level=1";
$q3 = $conn->prepare($sql3);
$q3->execute(array("$level2downlines"));
$first_row = true;
while($r3 = $q3->fetch(PDO::FETCH_ASSOC)){
$level3downlines = $r3['member'];
if ($first_row){
echo "make orange juice";
$first_row = false;
}else{
echo "make all juice";
}
}
更新:Michael Berkowski的答案更好更快。