While writing a login system for a web project Im working on I came across the problem of binding an unknown number of parameters and found this function on the php manual pages. I always like to fully understand an peice of code I put into anything Im working on and Im quite stumped as to how a few sections of this function work.
Ive commented everything I think i understand(if im wrong please let me know) and left my major questions in the comments:
<?php
function getresult($stmt) {
//Define var for holding the result
$result = array();
//asign metadata of the statments result
$metadata = $stmt->result_metadata();
//grab the feilds from the metadata and assign to var
$fields = $metadata->fetch_fields();
//for loop with internal break
for (;;) {
//pointers array (not sure why this is an array and not a stdClass)
$pointers = array();
//row empty class
$row = new stdClass();
//set pointers array to the value of the passed statement (casting $pointers to mysqli_stmt class I assume(?)
$pointers[] = $stmt;
//iterate through all fields
foreach ($fields as $field) {
//each time set $fieldname to the name from the current element of $fields
$fieldname = $field->name;
//?? this is my big issue no idea whats going on here $row hasnt been set from what i can see, and no idea why its being refered to by reference and not value
$pointers[] = &$row->$fieldname;
}
//call bind result for all values
call_user_func_array(mysqli_stmt_bind_result, $pointers);
//internal break if
if (!$stmt->fetch()) {
//if there is nothing left to fetch break
break;
}
//set the result
$result[] = $row;
}
//free resources
$metadata->free();
//return result
return $result;
}
?>
Thanks in advance!
It creates a new
stdClass(pretty much like an empty array) for each row.With
$pointers[] = &$row->$fieldname;a reference to the various fields of the object is stored.After that,
mysqli_stmt_bind_resultis used to tell mysqli where to store the data of the next row. When calling$stmt->fetch(), mysqli assigns it to the references in$pointersand thus to the fields in the$rowobject.$pointersis an array becausemysqli_stmt_bind_resultexpects one. Objects do not have 0..n fields but rather named values – so to assign columns based on their position using a non-associative array makes much more sense.It does pretty much the same what
mysqli::fetch_object()does.