I am trying to retrive data from database using FECH_ASSOC
in order the output will took like this
last1 first1 last2 first2 & last3 first3
last4 first4 & last4 first4
this is the database i have:
ID index first last
--------------------------
1 1 first1 last1
2 1 first2 last2
3 1 first3 last3
4 2 first4 last4
5 2 first5 last5
Each output row shoud defined by the index value. as you can see in the output example I need the organ before the last one in any array to be separetad because i need to put the &
before it.
this is the code i came up with:
//HERE I RETRIVE ALL THE DATA FROM THE DATABASE.
$sql = "SELECT COUNT( * ) FROM table WHERE index= $index";
$result = $dbh->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
//ASSOC DEFINITION
$sth = $dbh->prepare("SELECT * FROM table WHERE index= $index);
$sth->execute();
$value = $sth->fetch(PDO::FETCH_ASSOC);
//THIS IS WHERE I CALL ALL THE ROWS BY THEIR VALUE
$return = "";
$fname = $value['fname'];
$lname = $value['lname'];
$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++){
$value = $sth->fetch(PDO::FETCH_ASSOC);
$fname[$counter] = !empty($fname[$counter]) ? $fname[$counter] : '';
$return .= $lname. ', ' . $fname;
}
$fname[$counter] = !empty($fname[$lastItem]) ? $fname[$lastItem] : '';
$return .= "&" . $fname. ', ' . $lname;
$return .= ' ';
return $return;
this is the output i get: last3 first1 last1 first1 & last2 first1
last5 first4 & last4 first4
I cant figure out what i am doing wrong. I tryied using foreach but i didnt manage to separete the last pair of values here.
I am stuck with this this for a few days. any help would be great.