0

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/>";
    }

} ?>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.