how to use one query for two loops

て烟熏妆下的殇ゞ 提交于 2020-01-14 04:13:09

问题


how can i write query in this situation: this is the query

$gdQuery = $conn->query("blah blah ");

i want to use the above query for while loop that is two time.

  1. is to retrive skillname (name)
  2. is to retrivestudent name (student_fname)

is it a correct approach if not how can i do that..?

<table>
<thead>
    <th>Paricipant</th> 
    <?php while($gdData = $gdQuery->fetch_assoc()) {  ?> 
    <th class="text-center"><?php echo $gdData['name']; ?></th> <?php } ?> 
    <th>Score</th> 
</thead>
<tbody>
    <tr>
        <?php while($gdData = $gdQuery->fetch_assoc()) {    ?>
        <td><?php echo  $gdData['student_fname']; ?></td> <?php }   ?> 
        <td style="line-height:45px">Score</td> 
    </tbody> 
</table>

My problem is when i write this the second while loop is not working


回答1:


fetch_assoc retrieves one row from query result. You can use it until you run out of rows in that result set. By calling it multiple times you are moving towards the end of result set. That is reason why there is nothing to do for second while loop. RTD http://php.net/manual/en/mysqli-result.fetch-assoc.php

Use fetch_all to get all rows before you start iterating and store them in variable. Use that variable for your iterations.

Alternatively you may try to use data_seek to reset pointer in result set to beginning after first while loop. http://php.net/manual/en/mysqli-result.data-seek.php




回答2:


I would suggest to separate the data retrieval from the output.

The first part should retrieve all data from the table (name, student_fname) and store it in two arrays.

The second part reads the arrays and produces the html table.

That way you have to run the costly query only once.




回答3:


Use the PDOStatement::fetchAll() method to get all your columns and rows.

Then, use the PDO::FETCH_ASSOC $fetch_style parameters of the PDOStatement::fetchAll() method to get an associative array.

$gdQuery = $conn->query('blah blah ');
$gdDatas = $gdQuery->fetchAll(PDO::FETCH_ASSOC);

You will then have one query achieved with your datas. You can then access your datas associatively.




回答4:


If you want to use the same loop at two places on a page but want to fetch different column names then its not an issue.

$gdQuery = $conn->query('blah blah ');
$gdDatas = $gdQuery->fetchAll(PDO::FETCH_ASSOC);

Write this query at top of the page and use $gdDatas at different places just. Or if you want to use queries at muliple places then change the variable names and use it.



来源:https://stackoverflow.com/questions/41197430/how-to-use-one-query-for-two-loops

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