问题
Is there a way to enable the use of fetch_assoc()
several times on the same page with prepared statements?
$data = $conn->prepare("SELECT * FROM some_table WHERE id=?");
$data->bind_param('i',$id);
$data->execute();
$result = $data->get_result();
I'd like to be able to use fetch_assoc()
on the same page as many times as I want as many different ways I want. If I want to loop twice, I should be able to do that. If I want to loop and do a single fetch, I should also be able to do that. Right now it seems, once fetch_assoc()
is being used once, it cannot be used again on the same page.
In a loop
while($row = $result->fetch_assoc()){
...
}
Single fetch
$user = $result->fetch_assoc();
$first_name = $user['first_name'];
回答1:
You can use mysqli_result::data_seek to reset the result pointer after each usage so you can loop over the results multiple times. For example:
while($row = $result->fetch_assoc()){
...
}
$result->data_seek(0);
while($row = $result->fetch_assoc()){
...
}
回答2:
While technically possible (Nick shows how) to rewind the mysqli_result
object, many people find it cumbersome to work with mysqli_result
at all. It's much easier to fetch all the records into a PHP array and work with a multidimensional array instead of the mysqli_result
object.
$result = $data->get_result()->fetch_all(MYSQLI_ASSOC);
This way you can do whatever you want with this array. You can filter, you can loop many times, you can use all the standard array functions in PHP.
$resultsFiltered = array_filter($results, fn($e) => $e['someColumn']>200);
foreach($resultsFiltered as $row) {
// only records with someColumn > 200
}
来源:https://stackoverflow.com/questions/59806715/how-can-i-use-mysqli-fetch-assoc-several-times-with-prepared-statements-on-sam