I have an SQL query which outputs 1000 sql entries (sometimes less than 1000). I want the first result and the last result to be unique.
Is the best way to do this, to run it through an IF statement 1000 times, just to customize the first and last row? or is there a better way?
Example:
$sql=("SELECT * FROM `table` LIMIT 0, 1000");
$q = $conn->prepare($sql);
$q->execute($executearray);
$q->setFetchMode(PDO::FETCH_BOTH);
$i = 0;
$total = $q->rowCount();
while ($r = $q->fetch()){
$i++;
// first result
if ($i == 1) {
echo "<div>" . $r['id'] . "</div>";
echo "<div>" . $r['image'] . "</div>";
echo "<div>" . $r['text'] . "</div>";
// last result
} elseif ($i == $total) {
echo "<div>" . $r['somethingelse'] . "</div>";
// all other results
} else {
echo "<div>" . $r['image'] . "</div>";
echo "<div>" . $r['text'] . "</div>";
}
}
Is there a way to do something like this…?
$sql=("SELECT * FROM `table` LIMIT 0, 1000");
$q = $conn->prepare($sql);
$q->execute($executearray);
$q->setFetchMode(PDO::FETCH_BOTH);
// first result
echo "<div>" . $r[0]['id'] . "</div>";
echo "<div>" . $r[0]['image'] . "</div>";
echo "<div>" . $r[0]['text'] . "</div>";
// results 2-999
while ($i <= $total - 1) {
echo "<div>" . $r['somethingelse'] . "</div>";
}
// last result
echo "<div>" . $r[$total]['image'] . "</div>";
echo "<div>" . $r[$total]['text'] . "</div>";
This avoid the IFs for the middle records by looping only for record
2tocount-1.That said, it will only save you a miniscule amount of cpu time. You’d be better concentrating efforts on expensive code, not something as trivial this.
Also, note that the for loop has an implicit IF in it:
$1<$total. Where as your loop was utilising the result from$q->fetch()to control the while loop. I’m even more sceptical as to how much cpu time this will save you. Without measuring actual cpu cycles it’s possible it’s not even measurable.