I created a while loop that produces random images for the user. Every time I load the page the while loop produces a random number of images. I would like for it to show 10 but it will produce anywhere from 3-10 images. I checked in the database and user_id is unique for every entry. I have no idea why it’s doing this. What is wrong with the code? I’ll also accept an answer that can point in a direction (tutorial link) to rewrite this code in a better way.
<?php
$query = mysql_query("SELECT `user_id` FROM `users` ORDER BY RAND() LIMIT 0, 10");
$r = 1;
while ($results_row = mysql_fetch_assoc($query))
{
$var_1 = $results_row['user_id'];
$getting_essentials = mysql_query("SELECT
`band_name`,`donated_money`,`donated_time` FROM `create_project` WHERE `user_id` =
$var_1");
$getting_results = mysql_fetch_assoc($getting_essentials);
$bandsname = $getting_results['band_name'];
if (isset($bandsname) === true) {
$donatedmoney = $getting_results['donated_money'];
$donated_time = $getting_results['donated_time'];
$var_2 = username_from_user_id($var_1);
$image_name = 'images/' . md5($var_2) . '_' . $var_1;
echo '<a href="' . $var_2 . '"><img src="' . $image_name . '" class="'.$r.'"
width="300" height="185"/></a>';
}
$r++;
}
?>
I see a couple of potential problems.
First, what is
var_2? It doesn’t appear to be set anywhere.Second, it appears that you will get as many images as there are unique user IDs in your table. This seems to me a bizarre way of trying to get ten images.
Third, the actual file names you’re using for the images are built using the user ID. It may well be that not all the files exist.
A way to check that last point is to simply do a “View Source” operation in your browser.
It may be that you’re always getting 123 images (assuming you have 123 distinct user IDs) but some of them don’t exist.
As a low-level debugging exercise, you can insert code to echo debug statements (in HTML format) so you can see what’s happening under the covers. This is often the quickest way to determine problems. In other words, pepper your code with things like:
By doing that and examining the output, it’ll make it a lot more obvious than trying to do static analysis on the code.