Reputation: 344
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.
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
Upvotes: 1
Views: 490
Reputation: 151
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.
Upvotes: 2
Reputation: 2504
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.
Upvotes: 2
Reputation: 862
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
Upvotes: 2
Reputation: 32697
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.
Upvotes: 2