在编写Web项目的登录系统时我正在处理我遇到绑定未知数量参数的问题,并在php手册页上找到了这个函数。我总是喜欢完全理解我所处理的任何代码中的一些代码,我对这个函数的几个部分如何工作感到非常难过。
我评论了我认为我理解的一切(如果我错了请告诉我)并在评论中留下我的主要问题:
<?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;
}
?>
提前致谢!
答案 0 :(得分:1)
它为每一行创建一个新的stdClass
(非常像一个空数组)。
使用$pointers[] = &$row->$fieldname;
存储对象的各个字段的引用。
之后,mysqli_stmt_bind_result
用于告诉mysqli存储下一行数据的位置。调用$stmt->fetch()
时,mysqli会将其分配给$pointers
中的引用,从而分配给$row
对象中的字段。
$pointers
是一个数组,因为mysqli_stmt_bind_result
需要一个。对象没有0..n字段而是命名值 - 所以使用非关联数组根据位置分配列更有意义。
它与mysqli::fetch_object()
完全相同。