I am struggling to store the sql fetched results in an array. I tried alot of suggested methods I found on the internet and I cant get it to work. I am obviously doing something wrong. This is the latest code I am testing atm:
// The following code is place after prepare() and mysqli_stmt_execute($stmt)
mysqli_stmt_bind_result($stmt, $colDescription);
$descArray = array();
$i = 0;
/* fetch values and store them to each variables */
while (mysqli_stmt_fetch($stmt)) {
$fetch = $colDescription;
$descArray[$i] = $fetch;
$i++;
}
//For testing to see what echos in that array
foreach($descArray as $v) {
echo $v;
}
In the above code, when I echo the array, only the last row of the table is outputted. So I think I am basically overlapping the values to the last row and its not really storing all the fetched values in an array. What am I doing wrong here? Can someone guide me please?
I couldnt quite get it to work with mysqli
after trying for almost 2 days on this. So I have switched to PDO
and I found that was so much easier to deal with array results that are fetched. This is what I have used now in the PDO method and it works like a charm:
// The following code is place after PDO prepare() and execute()
foreach ($stmt as $row) {
// do something with $row
$description[] = $row['description'];
}
You can see how easy it was and it just took a couple of lines to do this. It was like a nightmare when I was trying to achieve the same with mysqli and I dont even know if it was going to be possible. I tried so many methods with no luck. Even if it was possible with mysqli I am quite sure it would have taken a long windy and dirty looking code just to achieve something simple like this. So its totally worth yet to make the switch to PDO.
I hope this helps to someone stuck on this like me...
As far as i understand the value of $colDescription
is overwriting. When you have it in the instruction
mysqli_stmt_bind_result($stmt, $colDescription);
Now when you call it here
$fetch = $colDescription;
It gets the value initilized above so it is over writing. You need to do this.
unset($colDescription);
Before the loop so that it gets new value from mysqli_stmt_fetch($stmt)
. So your code should be something like this
mysqli_stmt_bind_result($stmt, $colDescription);
$descArray = array();
$i = 0;
unset($colDescription);
while (mysqli_stmt_fetch($stmt)) {
$fetch = $colDescription;
$descArray[$i] = $fetch;
$i++;
}
echo '<pre>';
print_r($descArray);