I have a fetch_assoc query that will grab 14 rows, but I want the FIRST result displayed so it is differnet to the others, then the rest are just ordinary.
$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
while($events = $site_events->fetch_assoc()) {
if( first result???? ) { //this is where im stuck
echo $events['title'], 'FIRST RESULT';
}
//then display others like a normal list..
echo $events['title'], '<br />';
}
You can fetch first line outside the "while" and then continue normally. But first you should probably check if there are data selected just in case:
$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
if($db->field_count){
$event = $site_events->fetch_assoc();
echo $event['title'], 'FIRST RESULT';
while($events = $site_events->fetch_assoc()) {
//then display others like a normal list..
echo $events['title'], '<br />';
}
}
I based mine on Yatin Trivedi's answer, but removed the increment with a variable which I unset. You wont notice the difference, but this is a bit faster. This is because the $i++
doens't have to be called every itteration. Also, unset()
is really fast.
Edit: That answer started with $i=0
and a $i++
, now it doesnt anymore :)
$hasNotLooped = true; // set it before you run the loop
$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
while($events = $site_events->fetch_assoc()) {
if( $hasNotLooped ) {
echo $events['title'], 'FIRST RESULT';
unset($hasNotLooped);
}
//then display others like a normal list..
echo $events['title'], '<br />';
}
$tmp=true;
$site_events = $db->query("SELECT * FROM site_events ORDER BY time ASC limit 14");
while($events = $site_events->fetch_assoc()) {
if( $tmp) { //this is where im stuck
echo $events['title'], 'FIRST RESULT';
$tmp=false;
}
else
{
//then display others like a normal list..
echo $events['title'], '<br />';
}
}