Mohammad Saberi Mohammad Saberi - 11 months ago 59
MySQL Question

Reuse fetched data in PHP and MySQL with PDO

I'm writing an accounting system with PHP and MySQL and using PDO for working with database. In the payment page, I must have 2 drop down lists from defined accounts.

At the first, I've used a simple query to fetch all records for accounts.

$sql = "SELECT id,title FROM tbl_accounts WHERE uid = ? ORDER BY title";
$q = $db->prepare($sql);

I have put fetched rows in a drop down list and everything was ok.

<select name="account_id2" class="medium" id="account_id2">
<option value="null">---</option>
while ($r = $q->fetch()) {
echo '<option value="'.$r['id'].'">'.$r['title'].'</option>';

But when I wanted to make second drop down list using fetched records, nothing have been shown. So I thought I had to create another query for it. I did it and second one made correctly.

But my question is: Can not we use fetched data more than 1 time ? If I needed 3rd drop down, I had to write another query?

Answer Source

Depending on your conditional loop, you may need to reset the array pointer using reset().


To reset a result set you can use data_seek() or built a separate array as noted in the other answers.