简体   繁体   中英

While loop only executing once

I have a form that displays contact email addresses in text boxes, and drop down selections for titles for those corresponding emails.

TitleSelect1 Email1 TitleSelect2 Email2 ....

the emails have a title_id set, and the select list selects the existing Title. This works fine for the first contact, but the rest will only display the email address, the title dropdown is empty.

<?php

while ($row2 = mysql_fetch_array($Contact_list)) {
    ?>
<tr>
    <td align="right"><select id="Contacts_title" name="Contacts_title[]">
        <?

        while ($row3 = mysql_fetch_array($title_list)) { //put the contact titles into an array

            if ($row3['title_id'] == $row2['title_id']) {
                ?>
                <option value="<? echo $row3['title_id'] ?>" selected="true"><? echo $row3['title'] ?>!</option>';
                <?
            }

            else {
                ?>
                <option value="<? echo $row3['title_id'] ?>"><? echo $row3['title'] ?> </option>';
                <?
            }
        }

        ?>
    </select>
    </td>
    <td align="left"><input type="text" id="Contacts" name="Contacts[]" value="<? echo $row2['email'] ?>"/></td>
</tr>
<?
    $count++;
} 

mysql_fetch_array() only goes through the results of a given query once. Since you're not executing the title_list query every time though your contact list loop, it's still at the end of the query results when you start every iteration after the first.

What you need to do is take all the results from your title_list query, put them into an array, and iterate over that for each of your contacts.


Here's a general example of how you'd do this (with extraneous bits trimmed out):

$contact_list = //some query
$title_list = //some query

$titles = array();
while($title_ar = mysql_fetch_array($title_list)) {
  $titles[] = $title_ar;
}

while($contact_ar = mysql_fetch_array($contact_list)) {
    // some stuff
    foreach($titles as $title) {
        // do something with each title
    }
}

您应将行放入变量中,并在while循环后回显。

once the inner while loop executes once fully, you wont get any more values in that mysql_fetch_array call again. Since the cursor reached the end of rows.

You should store the results of the inner while loop into a php array and then iterate through this array every time within the inner while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM