I'm trying to do a for loop inside a foreach loop.
I have a table in my database as follows:
ID | Fname | Lname
------------------------
1 Bart Simpson
1 Mickey Mouse
2 Peter Griffin
2 Clark Kenet
2 David Johnson
i call the data from the database (and it works, tested on phpmyadmin), I want the data to be shown on the page by the ID value for exemple:
Bart Simpson, Mickey Mouse & Peter Griffin
Clark Kenet & David Johnson
as you see there in an "&" before the last name at any row but that isnt my problem.
this is the code i wrote:
//HERE I RETRIVE ALL THE DATA FROM THE DATABASE.
$query = $dbh->query(" SELECT *
FROM table
WHERE ID= '{$ID}'
");
//THIS CODE SHOWS THE NUMBER OF ROWS WITH THE CURRENT ID
$sql = "SELECT COUNT( * ) FROM table WHERE ID= '{$ID}'";
$result = $dbh->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
//THIS IS THE FOREACH IN WHICH I CALL ALL THE ROWS BY THEIR VALUE
foreach ($query as $key =>$value) {
$value['wFname'][$key] = !empty($value['wFname'][$key]) ? $value['wFname'][$key] : '';
$numRow = $number_of_rows-2; // THE ITEM BEFORE THE LAST ONE IN THE ARRAY
$lastItem = $number_of_rows-1; //LAST INDEX IN THE ARRAY
for($counter = 0; $counter = $numRow; $counter++){
return $value['wLname'][$counter] . ', '. $value['wFname'][$counter];
}
return "&" . $value['wLname'][$lastItem] . ', '.$value['wFname'][$lastItem] ;
return ' ';
};
with this code i get only the first pair of names with each id. any help would be great.