-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)) ?>

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. Commented Sep 2, 2019 at 4:11
  • Also see stackoverflow.com/questions/5612656/…. Commented Sep 2, 2019 at 4: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 Commented Sep 2, 2019 at 4:24
  • Also see, stackoverflow.com/questions/47580890/… obviously plug-in my answer ;p Commented Sep 2, 2019 at 4:41

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

How do you know that the OP is using CodeIgniter?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.