-4

I am looking to have a random number generate for an order id number for a website I am working on. It uses MySQL to store the orders with the order id being the primary key, so they cannot match. The order id is placed into an input field that will be used to insert into the database, so I cannot use MySQL to generate the number.

I have tried $numbers = range(1, 20); shuffle($numbers); But just get "Array" in the input field.

Right now, all I have is <?php echo(rand(1,1000)) ?>

jcarnes93
  • 11
  • 4
  • Either leave the primary key generation to your database (auto-incremented field), or use a random value with low collision probability like a UUID. – Robby Cornelissen Sep 02 '19 at 04:11
  • Also see https://stackoverflow.com/questions/5612656/generating-unique-random-numbers-within-a-range-php. – Obsidian Age Sep 02 '19 at 04:11
  • I have edited to include that I have tried the ```$numbers``` but all I get is "array" @RobbyCornelissen I need it to generate a number so it can transfer to another page via URL – jcarnes93 Sep 02 '19 at 04:24
  • Also see, https://stackoverflow.com/questions/47580890/generate-random-number-of-6-digit-length-with-at-least-n-unique-digits-in-php/47581305#47581305 obviously plug-in my answer ;p – Lawrence Cherone Sep 02 '19 at 04:41

1 Answers1

1

Try to call this function according your framework. This function is done by CI Framework to check random number already exist in database or not.

get_random_number('tbl_order','id');

function get_random_number($table_name,$field_name)
{
    // Create a random id
  $random_unique  =  sprintf('%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));

    //$random_unique = random_string('alnum', 6);
    // Make sure the random id isn't already in use
  $CI = get_instance();
  $CI->db->where($field_name, $random_unique);
  $query = $CI->db->get_where($table_name);

  if ($query->num_rows() > 0)
  {
    // If the random id is already in use, get a new number
    $this->get_random_number();
  }
  return $random_unique;
}
Vaibhavi S.
  • 1,083
  • 7
  • 20