I have some problems with $stmt->fetch()
I have a variable called $row which consists of $row['id'] and $row['name']. In the $stmt->fetch() loop I want to append the row to a $result array. But if print the $result array it only consists out of the last row.
Here is my code:
function queryResult($sql, $params, $columNames) {
$result = [];
$row = [];
$bindVars = [];
for ($i = 0; $i < sizeof($columNames); $i++) {
$bindVars[] = &$row[$columNames[$i]];
}
$stmt = $this->query($sql, $params);
call_user_func_array([$stmt, 'bind_result'], $bindVars);
while ($stmt->fetch()) {
print_r($row);
echo '<br>';
array_push($result, $row);
print_r($result);
echo '<br><br>';
}
return $result;
}
And this is the result:
Array ( [id] => 2 [name] => Test2 )
Array ( [0] => Array ( [id] => 2 [name] => Test2 ) )
Array ( [id] => 3 [name] => Test3 )
Array ( [0] => Array ( [id] => 3 [name] => Test3 ) [1] => Array ( [id] => 3 [name] => Test3 ) )
In line 14 I think while($row=mysqli_fetch_array($stmt))
should be used.
function queryResult($sql, $params, $columNames) {
$result = [];
$row = [];
$bindVars = [];
for ($i = 0; $i < sizeof($columNames); $i++) {
$bindVars[] = &$row[$columNames[$i]];
}
$stmt = $this->query($sql, $params);
call_user_func_array([$stmt, 'bind_result'], $bindVars);
while ($stmt->fetch()) {
print_r($row);
echo '<br>';
$arr_tmp = array();
foreach($row as $k=>$v) {
$arr_tmp[$k] = $v;
}
array_push($result, $arr_tmp);
print_r($result);
echo '<br><br>';
}
return $result;
}