Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

php issues

i have a table , i want to check if there is no record in the photo table in mysql, then it will show 2 empty <td> ,assume my photo table only have 1 record, so only the first row has record but the others should not but two empty td. anthing i am wrong .^^ thank you.

here is my code

<table border="0" cellpadding="0" cellspacing="0" class="member_table"> <thead> <!-- *** 2: Define HTML table headers --> <tr> <th>Product id</th> <th>Product Name</th> <th>Product Description</th> <th>Unit Price</th> <th>Photo name</th> <th>Photo</th> <th>Action</th>

</tr> </thead>

<tbody> <?php $sql = "SELECT * FROM products"; $result = mysqli_query($conn, $sql); $sql_2 = "SELECT p.* FROM photos p JOIN products p2 on p2.pid = p.pid"; $result_2 = mysqli_query($conn, $sql_2);

?> <?php if ($result && mysqli_num_rows($result) > 0): ?> <?php while($row = mysqli_fetch_assoc($result)): // fetch all rows one by one ?>

<!-- *** 3: Build HTML table listing --> <tr> <td><?php echo $row['pid']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['description']; ?></td> <td><?php echo $row['unit_price']; ?></td> <?$sql_2 = "SELECT p.* FROM photos p JOIN products p2 on p2.pid = p.pid"; $result_2 = mysqli_query($conn, $sql_2);?> <?php if ($result_2 && mysqli_num_rows($result_2) > 0): ?> <?php $row_2 = mysqli_fetch_assoc($result_2); // fetch all rows one by one ?> <?php if(!empty($row_2)): ?> <td> <?php echo $row_2['file']; ?> </td>
<td> <img src="images/<?php echo $row_2['file']; ?>" /> </td>

        <?php endif; ?>



<?php else: ?>

    <td>
        <?php echo 'nothing'; ?>
    </td>   
    <td>
        <?php echo 'nothing'; ?>
    </td>
<?php endif; ?>

<td>

<a href="product.php?action=edit&pid=<?php echo $row['pid']; ?>">Edit</a> | <a href="product.php?action=delete&pid=<?php echo $row['pid']; ?>">Delete</a> </td> </tr> <?php endwhile; ?> <?php else: ?> <tr> <td colspan="3">- No record found -</td> </tr> <?php endif; ?> </tbody> </table>

1 Answer

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

You need a while loop to handle this code:

$row_2 = mysqli_fetch_assoc($result_2)

(You do it correctly for the $row variable but not for this $row_2 variable.)

Does that help?