Search code examples
phprandom

Using `random_int()` instead of `rand()`


I am currently using rand() to select a random result from a table using a simple rand() and where SQL query.

Existing code:

private function doPreEventStart($user) {
  $row = db_fetch_item("SELECT resultid FROM ResultPackage
      where ResultPackage.slotid like '{$this->curSlotId}'
      and ResultPackage.PackageID like '%{$user->packageid}%'
      ORDER BY RAND() LIMIT 1");
  $this->curResultId = $row['resultid'];

I would like to change this to use random_int instead as this provide more genuine randomness which is needed for the application.

I have tried this but it is not working:

  private function doPreEventStart($user) {
      $row = db_fetch_item("SELECT resultid FROM ResultPackage
        where ResultPackage.slotid like ‘%{$slot_id}'
        and ResultPackage.PackageID like '%{$user->packageid}%'
        ORDER BY resultid asc LIMIT 1");
        $this->MinResult = $row['resultid'];
    var_dump(random_int($this->MinResult,$this->MaxResult) + ", SLOTID=" + $slot_id);
    }

Please can someone help to fix the above code.


Solution

  • It looks like you're trying to get a single item with your db_fetch_item function, and then perform some randomness with that one item, which will be the source of it not working.

    Depending on the package you should have a function that will return the array of matching rows from your query - I'd expect there to be a db_fetch_array.

    Once you have an array of items, selecting a single item is easiest using array_rand which gives you the key of a random element (but not the element itself, so you have to look up from the array using that random key).

    Try this:

      private function doPreEventStart($user) {
          $data = db_fetch_array("SELECT resultid FROM ResultPackage
            where ResultPackage.slotid like ‘%{$slot_id}'
            and ResultPackage.PackageID like '%{$user->packageid}%'
            ORDER BY resultid asc LIMIT 1");
    
            // Select random element from the array
            $slot_id = $data[array_rand($data)];
    
            var_dump("SLOTID=" + $slot_id);
        }