<?php
function read()
{
$parameters = array();
$results = array();
$mysql = new mysqli('localhost', 'root', 'root', 'db') or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT body FROM posts') or die('Problem preparing query');
$stmt->execute();
$meta = $stmt->result_metadata();
while ( $field = $meta->fetch_field() ) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ( $stmt->fetch() ) {
$x = array();
foreach( $row as $key => $val ) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
}
$results = read();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>untitled</title>
</head>
<body>
<?php foreach ($results as $row) : ?>
<p> <?php echo $row['body']; ?> </p>
<?php endforeach; ?>
</body>
</html>
help with understanding call_user_func_array and & reference operator
Read this, its a good explanation of that function.
http://www.unemployeddeveloper.com/239_lesser-known-php-functions-call_user_func_array/
thank you for attention. but can you explain it on my code
original source is
http://net.tutsplus.com/tutorials/ph...ed-statements/
i tested it. i want to know what happens there
while ( $field = $meta->fetch_field() ) {
$parameters[] = &$row[$field->name];
}
That piece is creating two arrays with the same number of elements, where $parameters is numerically indexed but $row is associative using the field names as keys. Since the =& operator is used, each corresponding array element references the same value, which will initially be null. ($parameters[0] references $row['body'] in this case.)
$parameters is then used as the 2nd arg to call_user_func_array(), as it wants the supplied array to be numerically indexed. Each element of $parameters then becomes a bound parameter for the bind_result function called by the call_user_func_array(). Since the elements of $row are references to the same values, $row is then used in the while(fetch) loop so that the field names can be gotten from its array keys instead of the numerical indexes in $parameters.
Thank you very much. now i understood the reference operator why used here
Thanks again very much