English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

$random=mysql_query("
SELECT badge_number FROM badge_numbers ORDER BY rand() limit 1");

{

echo $random;
}


It just spilts out resource id4 for some reason??

2007-08-12 12:35:13 · 2 answers · asked by jeff lemon 1 in Computers & Internet Programming & Design

2 answers

Big D is nearly correct, but does not explain the WHY!
When you do a SELECT operation, it returns an array that you must FETCH to be able to display.
Since your querry ends with "limit 1", you do not have a series of records, but only ONE.
Your querry does not return any error either (bad practice),
In that case use:
$query = "SELECT badge_number FROM `badge_numbers ORDER BY rand() LIMIT 1";
$list = mysql_query($query) or die("Query failed : " . mysql_error()); // this will show errors.
$lst = mysql_fetch_array($list); // this fetches the array
$random = $lst[index_in_the_field_list];
mysql_free_result($list); // NEED to free you array (you are using MySQL ressources: memory leak).
Finally, you ORDER by random, while you just want ONE badge at random... wrong approach: it will always return the first record encountered (always the same), hence, the same badge number.

Your solution (one of them)
$query = "SELECT * FROM `badge_numbers`"; // no limit, selects all.
$list = mysql_query($query) or die("Query failed : " . mysql_error()); // this will show errors.
$i=0; // good practice to init any variables.
while ($lst = mysql_fetch_array($list)) // this fetches the arrayS
{
$badges[$i] = $lst[0]; // assuming badge_number is the first field in the list (0). This fetches badge_numbers and store them in an array.
$i++;
}
mysql_free_result($list); // remember to free the ressources
$random_badgeno = rand(0,$i-1); // rand generates a number from 0 to the number of badges.
$random_badge = $badges[$random_badgeno];

A note: "it spills out ressource id4": you have 3 other arrays you have forgotten to free before calling this function!
Use
mysql_free_result(ressourceid); // as specified above.

2007-08-12 20:53:39 · answer #1 · answered by just "JR" 7 · 0 1

after $random = mysql_query("
SELECT badge_number FROM badge_numbers ORDER BY rand() limit 1");
while($row = mysql_fetch_array($random)){
print $row['badge_number'];
}

2007-08-12 12:42:21 · answer #2 · answered by Big D 4 · 0 0

fedest.com, questions and answers