View Full Version : recordset to array

04-30-2006, 01:24 PM
I have a record set that gets the stock id's from a database. What i want to do is load all the stock id's into an array and randomly choose from them to display a random product in a area on a website. This would be loaded into a session variable so that each visit will display a different product and it will not change between pages. I have done a way already but this doesn't allow for gaps in the product id's (example: you delete a product and the id is 3, but the random number generator doesn't know that, so it trys to display the product even though it has been deleted). Can anyone show me a code example of this.

04-30-2006, 08:37 PM
By using the database to choose it at random, it wont choose a record that doesnt exist. This keeps the used id's in a session array like you suggested. You could try something like this (obviously, change the variables and table names to what you actually need!)


include 'config.php';


$filter = '';

if (isset($_SESSION['used'])) {
$filter .= " WHERE";
$done = 0;
foreach($_SESSION['used'] as $v) {
if ($done==0) {
$filter .= " id<>$v";
$done = 1;
} else {
$filter .= " AND id<>$v";

$sql = "SELECT id FROM products$filter ORDER BY RAND() LIMIT 1";
$result = mysql_query($sql);

if (list($id) = mysql_fetch_array($result)) {

if (!isset($_SESSION['used'])) {
$_SESSION['used'] = array("$id");
} else {
$_SESSION['used'][ ] = $id;

print "this id: $id<br>";

} else {

print "no more records...";


//print $filter; // for bug checking stuffs...


Hope this helps, any problems?