random number same every iteration

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
slash_gnr3k
Forum Commoner
Posts: 43
Joined: Tue Nov 28, 2006 6:41 pm

random number same every iteration

Post by slash_gnr3k »

i am having a small problem with random numbers. I have a script which does exactly what i want it to do - generate a random number which is an id for a database table, gets the name and prints. this all works fine. however i want to do this over again and am having problems:

Code: Select all

$foo = true;
		while ($foo = true)
		{
			//get a random number
			srand(time());
			$random = (rand(1, 21));

			include 'connect.php';

			//select all dishid values from the dishes table
			$idexists = @mysql_query("SELECT dishid FROM dishes");
		
			if(!idexists)
			{

				echo"fail";

			}

			//add all id's to an array
			$idarray;
			$iterationnumber = 0;
			while ($row = mysql_fetch_array($idexists))
			{

				$idarray[$iterationnumber] = $row['dishid'];
				$iterationnumber++;							
				//all valid id numbers are now stored in an array
			}

			//if the random number generated is in the array it is a valid id. if not, keep generating until valid id found
			
			while (!in_array($random, $idarray)) 
			{

				$random = (rand(1, 21));

			}

		

			$getrandomname = @mysql_query("SELECT name FROM dishes WHERE dishid = '$random'");

			if(!$getrandomname)
			{

				echo"fail";

			}

			while ($row = mysql_fetch_array($getrandomname))
			{

				$dish1name = $row['name'];
				echo "$dish1name <br />";

			}
		}
obviously this will loop forever but that condition is only there to demonstrate my problem. what this does is it outputs "$dish1name" over and over. Why is there not a new value in $random when the loop re-iterates?
thanks
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Your example code has all sorts of issues. What exactly is the problem? Are you getting values output, or is the variable name actually outputting. What is it exactly that is happening?
slash_gnr3k
Forum Commoner
Posts: 43
Joined: Tue Nov 28, 2006 6:41 pm

Post by slash_gnr3k »

the name outputs as it is supposed to but does it over and over again with the same value. what i want is a new random value every iteration
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

See the parenthesis around the call to rand(1, 21)? That is causing $random to be evaluated as a boolean I believe.
slash_gnr3k
Forum Commoner
Posts: 43
Joined: Tue Nov 28, 2006 6:41 pm

Post by slash_gnr3k »

i changed that, same thing happens. i changed the condition as i want seven different random values

Code: Select all

$foo = 1;
		while ($foo <8)
		{
			//get a random number
			srand(time());
			$random = rand(1, 21);

			include 'connect.php';

			//select all dishid values from the dishes table
			$idexists = @mysql_query("SELECT dishid FROM dishes");
		
			if(!idexists)
			{

				echo"fail";

			}

			//add all id's to an array
			$idarray;
			$iterationnumber = 0;
			while ($row = mysql_fetch_array($idexists))
			{

				$idarray[$iterationnumber] = $row['dishid'];
				$iterationnumber++;							
				//all valid id numbers are now stored in an array
			}

			//if the random number generated is in the array it is a valid id. if not, keep generating until valid id found
			
			while (!in_array($random, $idarray)) 
			{
			
				$random = rand(1, 21);

			}

		

			$getrandomname = @mysql_query("SELECT name FROM dishes WHERE dishid = '$random'");

			if(!$getrandomname)
			{

				echo"fail";

			}

			while ($row = mysql_fetch_array($getrandomname))
			{

				$dish1name = $row['name'];
				echo "$dish1name <br />";

			}
			$foo++;
		}
i get the same random value 7 times!
slash_gnr3k
Forum Commoner
Posts: 43
Joined: Tue Nov 28, 2006 6:41 pm

Post by slash_gnr3k »

sorted it. took out the srand(time()); line.
thanks
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

There are some other issues in the code. I am working on a quick cleanup at the moment. I'll post back in a bit.

And yes, the srand() was removed from my clean up.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Code: Select all

<?php
$foo = 0; // PHP is zero based, so it makes sense to stay in the theme 
while ($foo < 7)
{
    //get a random number
    $random = rand(1, 21);

    include 'connect.php';

    //select all dishid values from the dishes table
    /**
     * You should have some sort of error handling here
     * And you should not use error suppression @     
     */                 
    $idexists = mysql_query('SELECT dishid FROM dishes') or die(mysql_error());

    if (!$idexists)
    {
        echo"fail";
    }

    //add all id's to an array
    /**
     * WHAT DOES THIS DO?
     * 
     * Should it maybe be $idarray = array();                  
     */                 
    //$idarray;
    $idarray = array();
    $iterationnumber = 0;
    while ($row = mysql_fetch_array($idexists))
    {
        $idarray[$iterationnumber] = $row['dishid'];
        $iterationnumber++;                                   
    }

    //if the random number generated is in the array it is a valid id. if not, keep generating until valid id found
    while (!in_array($random, $idarray))
    {
        $random = rand(1, 21);
    }

    /**
     * This should have some sort of error handling also
     * As well as not using error suppression     
     */                 
    $getrandomname = mysql_query("SELECT name FROM dishes WHERE dishid = '$random'") or die(mysql_error());

    if (!$getrandomname)
    {
        echo 'fail';
    }

    while ($row = mysql_fetch_array($getrandomname))
    {
        echo $row['name'] . '<br />';
    }
    
    $foo++;
}
?>
slash_gnr3k
Forum Commoner
Posts: 43
Joined: Tue Nov 28, 2006 6:41 pm

Post by slash_gnr3k »

sorted. yes that was an array . what do you mean by error handling? doing something other than echo fail if an error occurs?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Sorry, I should have clarified that a bit...

Yes, do something other than echoing 'Fail'. This will not prevent execution of the remainder of the script. If what is coming out of the query is needed by the rest of the script, and the query fails, and the scripts continues execution... get my drift?
User avatar
AKA Panama Jack
Forum Regular
Posts: 878
Joined: Mon Nov 14, 2005 4:21 pm

Post by AKA Panama Jack »

And you should use mt_rand instead of rand because it generates a more random number sequence.
slash_gnr3k
Forum Commoner
Posts: 43
Joined: Tue Nov 28, 2006 6:41 pm

Post by slash_gnr3k »

ok. before i go ahead and catch errors theres one more piece of functionality i need to add.

Code: Select all

//select all dishid values from the dishes table that are vegetarian
			$idexists = @mysql_query("SELECT dishid FROM dishes WHERE vegetarian = 'Yes'");
i have modified this line so that only numbers from vegetarian recipes are selected. i need to do the whole thing again but without vegetarian. so there are two sets of random values .obviously i would change the code above from yes to no. is there a way which doesnt include copying all the code i wrote before to do this?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

If all you need is a random number between 1 and 21, this seems like it would be easiest...

Code: Select all

$nums = range(1,21);
shuffle($nums);
$num = $num[0];
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

slash_gnr3k wrote:is there a way which doesnt include copying all the code i wrote before to do this?
All of the code? Why? All you'd need is another query and make both query results into different arrays.
Post Reply