Trying to return a DB resultset as an array in my DAO:
I want to append string key-values to the array $retval in the below code. However, the array keeps getting overwritten each iteration instead of being appended to.
So at the end of the loop, I end up with 1 key-value instead of n pairs (n rows retrieved from the database). What am I doing wrong?
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
foreach($columns as $var) {
$retval[$var]=$row[$var];
}
}
var_dump($retval);
$retval ends up as ["name"=>"Japan","capital"=>"Tokyo"] instead of the expected ["name"=>"Korea","capital"=>"Seoul"...."Japan"=>"Tokyo"] where columns are name and capital.
It is because you are overwriting the same value (column name here.) Something like:
Instead use:
HTH.