Currently, you probably understood the idea of โโbinding to several variables. However, do not believe the warnings about using "SELECT *" with bind_result (). You can store your "SELECT *" instructions ... even on your server, requiring you to use bind_result (), but it's a bit complicated because you have to use PHP call_user_func_array () as a way to pass arbitrary (due to "SELECT" * ") the number of bind_result () parameters. Others in front of me provided a convenient function for this in other places on these forums. I include it here:
// Take a statement and bind its fields to an assoc array in PHP with the same fieldnames function stmt_bind_assoc (&$stmt, &$bound_assoc) { $metadata = $stmt->result_metadata(); $fields = array(); $bound_assoc = array(); $fields[] = $stmt; while($field = $metadata->fetch_field()) { $fields[] = &$bound_assoc[$field->name]; } call_user_func_array("mysqli_stmt_bind_result", $fields); }
Now, to use this, we do something like:
function fetch_my_data() { $stmt = $conn->prepare("SELECT * FROM my_data_table"); $stmt->execute(); $result = array(); stmt_bind_assoc($stmt, $row); while ($stmt->fetch()) { $result[] = array_copy($row); } return $result; }
Now fetch_my_data () will return an array of associative arrays ... everything is configured for JSON encoding or something else.
It is insidious what is happening here. stmt_bind_assoc () creates an empty associative array by the link you pass to it ($ bound_assoc). It uses result_metadata () and fetch_field () to get a list of returned fields and (with this only statement in the while loop) creates an element in $bound_assoc with that field name and adds a reference to it in the $ fields array. Then the $ fields array is passed to mysqli_stmt_bind_result. The really smooth part is that no actual values โโwere passed to $ bound_assoc. All fetching from the request occurs in fetch_my_data (), as you can see from the fact that stmt_bind_assoc() is called before while($stmt->fetch()) .
However, there is one catch: since the operator is bound to links in $ bound_assoc, they will change with every $stmt->fetch() . So, you need to make a deep copy of the string $. If you do not, all the rows in the $ result array will contain the same thing: the last row returned in your SELECT. So, I use the small array_copy () function that I found on Google:
function array_copy( array $array ) { $result = array(); foreach( $array as $key => $val ) { if( is_array( $val ) ) { $result[$key] = arrayCopy( $val ); } elseif ( is_object( $val ) ) { $result[$key] = clone $val; } else { $result[$key] = $val; } } return $result; }
Jemenake Aug 31 '14 at 21:29 2014-08-31 21:29
source share