I'm trying to dynamically bind mysql_stmt parameters and get the result in an associative array. I've found this post here on stackoverflow where Amber posted an answer with the following code:
Original post:
How to make a proper mysqli extension class with prepared statements?
"Assuming you're actually wanting to write your own version (as opposed to utilizing one of the existing libraries other answers have suggested - and those are good options, too)...
Here are a couple of functions which you may find it useful to examine. The first allows you to bind the results of a query to an associative array, and the second allows you to pass in two arrays, one an ordered array of keys and the other an associative array of data for those keys and have that data bound into a prepared statement:"
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);
}
function stmt_bind_params($stmt, $fields, $data) {
// Dynamically build up the arguments for bind_param
$paramstr = '';
$params = array();
foreach($fields as $key)
{
if(is_float($data[$key]))
$paramstr .= 'd';
elseif(is_int($data[$key]))
$paramstr .= 'i';
else
$paramstr .= 's';
$params[] = $data[$key];
}
array_unshift($params, $stmt, $paramstr);
// and then call bind_param with the proper arguments
call_user_func_array('mysqli_stmt_bind_param', $params);
}
I tried studying the code to understand what it does and I've made the second function work properly but I don't know what I should do to be able to utilize the first function. How do I use it to retrieve an array similar to mysqli_result::fetch_assoc()?
I want to be able to utilize the result in such a way like you used to do with:
while ($row = mysql_fetch_array($result)){
echo $row['foo']." ".$row['bar'];
}
Please help me to make some progress with this :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…