function givemetitles($table){
global $db;
$titles = '';
$stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
while($row = $stmt->fetch()){
$titles.=
"<div data-id=" . $row['id'] .
" class='linkl'>" . $row['title'] . "</div>\n";
}
echo $titles;
}
This writes the divs with linkl class successfully.
I need the first div to also contain the class linklactive - if possible.
Another approach is to set the class, and then clear it:
function givemetitles($table){
global $db;
$titles = '';
// set $first_class to the class you want for the first record
$first_class = ' linklactive';
$stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
while( $row = $stmt->fetch() ) {
// include $first_class in the $title value
// tweaked to use string interpolation
// Switched to PHP_EOL instead of \n
$titles.= "<div data-id='{$row['id']}' class='linkl{$first_class}'>{$row['title']}</div>" . PHP_EOL;
// reset $first_class to be empty string
$first_class = '';
}
echo $titles;
}
You can just count how many times you have looped, in the first run, you add that class...
function givemetitles($table,$row_active = 0){
global $db;
$titles = '';
$stmt = $db->query("SELECT id, title FROM " . $table . " ORDER BY title ASC");
$count = 0;
while($row = $stmt->fetch()){
if($count == $row_active){
$titles.="<div data-id=" . $row['id'] . " class='linkl linklactive'>" . $row['title'] . "</div>\n";
}else{
$titles.="<div data-id=" . $row['id'] . " class='linkl'>" . $row['title'] . "</div>\n";
}
$count++;
}
echo $titles;
}
Pretty? No not really, but it does the job.
That said, in this case the cale_b answer is more on point and "prettier". I am keeping this answer as you can define which row gets the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With