How can I use mysqli fetch_assoc() several times with prepared statements on same PHP page?

半世苍凉 提交于 2020-12-12 06:11:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!