Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder mic2100's Avatar
    Join Date
    Feb 2006
    Location
    Scunthorpe
    Posts
    562
    Thanks
    15
    Thanked 28 Times in 27 Posts

    Question recordset to array

    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.

  • #2
    Regular Coder
    Join Date
    Jun 2002
    Location
    United Kingdom Confused: Often
    Posts
    859
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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!)
    PHP Code:
    <?

    include 'config.php';

    session_start();

    $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?
    redhead


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •