0

Every time I add a new entry to the database I want a 10 digit unique number to be added along with it. See the code I have below with the random number but when the database gets big I want to ensure the number never gets generated again

$newIntent = new Invent;
$newIntent->house_number = rand();
$newIntent->company_name = "dsdasda";
$newIntent->address = "dsdasda";
$newIntent->email = "dsdasda";
$newIntent->mobile_cell = "dsdasda";
$newIntent->mobile_other = "dsdasda";
$newIntent->save();
echo "Saved";
Slygoth
  • 333
  • 6
  • 17
  • Is that table created by a migration? – Hedegare Sep 08 '17 at 16:07
  • 1
    Why not just use auto_increment, and set the ID to start where you want it? – aynber Sep 08 '17 at 16:07
  • @Jackowski yes it is created using migration – Slygoth Sep 08 '17 at 16:07
  • The accepted answer of https://stackoverflow.com/questions/8379033/php-quickest-way-to-generate-a-5-digit-number-not-already-in-mysql-db-column-w is quite interesting, having a second table with values not yet taken – Quezler Sep 08 '17 at 16:07
  • @aynber I didn't want to do it that way. But if this doesn't work ill have to do it that way. Wanted the numbers to be far apart – Slygoth Sep 08 '17 at 16:09
  • Also read this : https://stackoverflow.com/a/46071891/2815635 – Niklesh Raut Sep 08 '17 at 16:10
  • Would a hash of the other data fields be any use? You could generate a 10-digit hash in base 10, which would ensure (as much as anything else would, at least), that you would only get a clash if the other fields were also the same. – iainn Sep 08 '17 at 16:11
  • make use of `time()` rather than `rand()` function. `time()` returns the number of seconds referencing current date time, – Veshraj Joshi Sep 08 '17 at 16:11
  • Regardless of how you generate it, if you need to ensure that it's unique, you need to add a unique index for it. – Don't Panic Sep 08 '17 at 16:13

0 Answers0