Jump to content

Help with Array+MySQL+Random


Swarfega

Recommended Posts

Hey.

 

 

I'm trying to make a simple <a href> tag to Randomly take the user to a Random image from a Random user's album.

 

 

It works, in a way, but sometimes the values from the array returns as absolutely nothing, as in a NULL value, not even a '0'.

 

Here's the code

 



<?php
$getimagecountsql = "SELECT id FROM images";
$getimagecountquery = mysql_query($getimagecountsql);
$getimagecountrows = mysql_num_rows($getimagecountquery);
$getminimumsql = "SELECT MIN(id) FROM images";
$getminimumquery = mysql_query($getminimumsql);
$getminimumdata = mysql_fetch_assoc($getminimumquery);
$minimum = $getminimumdata['id'];
$randomimagearray = array();
$i = 0;
while($hehe = mysql_fetch_assoc($getimagecountquery)) {
array_push($randomimagearray, $hehe['id']);
$i = $i + 1;
}
$randomimage = $randomimagearray[rand(0, $i)];
echo "RIMAGE: ".$randomimage;
$getusersql = "SELECT albumid, uid FROM images WHERE id='".$randomimage."'";
$getuserquery = mysql_query($getusersql) or die(mysql_error());
$getuserdata = mysql_fetch_assoc($getuserquery);
$uid = $getuserdata['uid'];
$albumid = $getuserdata['albumid'];

echo'<br>>> <a href="album/visa.php?targetid='.$getuserdata['uid'].'&albumid='.$getuserdata['albumid'].'&image='.$randomimage.'">Slumpa Bild</a>';

echo "Användarid: " .$getuserdata['uid'];
echo "Albumid: ". $getuserdata['albumid'];


?>

 

Even after assigning the randomimage to take a random value between 0 and $i ($i being amount of records the array holds) it sometimes results in a null value.

 

 

(So it would be value of $randomimagearray[0] or $randomimagearray[$i])

 

 

Where did I go wrong?

Link to comment
https://forums.phpfreaks.com/topic/272670-help-with-arraymysqlrandom/
Share on other sites

I figured it out. Quite a silly mistake on my part, actually. But I'm new to Arrays, so meh.

 

 

Basically $i was being calculated as amount of entries added to the array, while an array starts at 0 not 1, one has to include a $i = $i -1; below the while loop.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.