Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am working on a directory where some of the listings have a images associated with them and others do not. I am wondering how I can write a loop within a loop to get my results.

Example, User selects state they want results from, query goes to DB requesting all listings in that state.

<?php
if (isset($_POST['searchButton'])) {

$state = $_POST['state'];

$query = "SELECT * FROM directory LEFT JOIN directory_images ON directory.id = directory_images.user_id WHERE directory.state = '$state' ";
$result = mysql_query($query) or die(mysql_error());

if (mysql_num_rows($result) == 0) {
    echo "<p>Sorry, there are no listings in '$state', check back soon!</p>\n";
}
else
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $id = $row['id'];
        $name = $row['name'];
        $address = $row['address'];
        $city = $row['city'];
        $state = $row['state'];
        $zip = $row['zip'];
        $has_support_pics = $row['file_name'];
        ?>

        <h4><?php echo $name ?></h4>
        <p><?php echo $address ?><br/>
            <?php echo $city . ' ' . $state . ', ' . $zip; ?><br/>
        </p>            
        <?php
        // check to see if ID has extra images
        if (isset($has_support_pics)) {
                    $query2 = "SELECT file_name FROM directory_images WHERE user_id = '$id'";
                    $result2 = mysql_query($query2) or die(mysql_error());
                    echo $query2.'<br/>';
                    ?>
                    <ul class="support_images">
                        <?php
                        while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
                            $support_image = $row['file_name'];
                            echo $support_image.'<br/>';
                                }
                            ?>
                    </ul>
                </div>
                <br/>
            </div>
            <?php
        }
        echo "<hr/>";
    }

} ?>

share|improve this question
add comment

1 Answer

Do NOT run queries in loops - use a join. Here is a tutorial: http://thewebmason.com/tutorial-parent-child-lists/

share|improve this answer
    
Thanks so much, this is very helpful! –  user1209945 Jun 7 '13 at 2:23
    
You're very welcome! –  Jessica Jun 7 '13 at 13:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.