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?

Edited by Swarfega
Link to comment
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.