same question guy 7 years ago: http://php.net/manual/en/mysqli-stmt.fetch.php#83073
this function takes metadata prepared sql query, $stmt, allows retrieve multiple rows many columns through array provided in $out.
function stmt_bind_assoc(&$stmt, &$out) { $data = mysqli_stmt_result_metadata($stmt); $fields = array(); $out = array(); $fields[0] = $stmt; $count = 1; while($field = mysqli_fetch_field($data)) { $fields[$count] = &$out[$field->name]; $count++; } call_user_func_array('mysqli_stmt_bind_result', $fields); } from here: http://php.net/manual/en/mysqli-stmt.fetch.php#82742
used such:
if ($stmt = $mysqli->prepare("select user_id, user_name user user_id=?")) { $stmt->bind_param('i', $userid); $stmt->execute(); $stmt->store_result(); $rowdata = array(); //create array hold data in returned row stmt_bind_assoc($stmt, $rowdata); //get values in row while ($stmt->fetch()) { //store events data $returneddata = new somerandomobject($rowdata['user_id'], $rowdata['user_name']); } } each time while loop looped through, $rowdata array update next row's column values.
the problem when try store $rowdata array's keys , values in array.
while ($stmt->fetch()) { //store events data $arrayofallrows[] = $rowdata; } because of references in stmt_bind_assoc, $arrayofallrows, after while loop executes, contain bunch of references last $rowdata array generated, instead of having 10 different rows, 10 copies of same row.
my question is: how references work in stmt_bind_assoc, , how can make entire $rowdata array copied $arrayofallrows?
$stmt->execute(); $rows = array(); stmt_bind_assoc($stmt, $row); while ($stmt->fetch()) { $rows[] = array_copy($row); } break; } function array_copy(array $array) { $result = array(); foreach($array $key => $val) { if (is_array($val)) { $result[$key] = arraycopy($val); } elseif (is_object($val)) { $result[$key] = clone $val; } else { $result[$key] = $val; } } return $result; }
Comments
Post a Comment