zac1987 zac1987 - 3 years ago 142
PHP Question

pdo how to check if it is 1st record that retrieve from database?

$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";
}
}


Let say output are 3 records from database "Zac", "Michelle", Andrew". "Zac" is the 1st record get from database, how to write the "if" statement to check if the records is 1st record or not?

Answer Source

First off, if the order of records returned matters, you must explicitly include an ORDER BY clause in your query to specify which column to sort results on. Otherwise, the order of rows returned is technically indeterminate.

To operate differently on the first fetched row than on later rows, you may simply call fetch() outside the loop first, then loop over the remainder. Each call to PDOStatement::fetch() will advance the rowset record pointer, so the while loop will only iterate the records after the one already retrieved.

// 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";
}

In practice, I don't often do operations while fetching rows unless the rowset is very large. Instead I would more likely retrieve all rows as an array where I can more easily perform array operations on the set.

// 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
}

Instead of using array_shift() in that way, when using $index => $row in the foreach loop, you could also check $index == 0 to operate on your first row. You may find this more understandable.

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.
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download