I am trying to run a loop and I create a unique 10 digit number and I want to add it to a table if it doesn't already exist. If it exist it should skip and continue but I need to keep track of how many have been added. I am running into some issues and need a little help.
I got a simple table called Codes. It has code(primary key), client_id and timestamps.
Couple of issues/questions.
It will enter the first code but then fails on duplicate key. It doesn't seem like it is using the new tmp_code.
Also got a question on how I can pass the 2 variables from the route to the controller. I am testing this by a simple get route but once implemented it will be a post which will tell the controller how many and the client_id would be grabbed by the logged in user data.
public function add_codes($how_many = 3, $client_id = '')
{
$how_many_added = 0;
$codes = [];
for ($i=0;$how_many_added<$how_many;$i++) {
$tmp_code = mt_rand(1000000000, 9999999999);
echo $tmp_code;
if (!Code::find($tmp_code)) {
echo "Adding New Code<P>";
$code = new Code;
$code->code = $tmp_code;
$code->client_id = $client_id;
$code->save();
$how_many_added ++;
$codes[] = $code;
} else {
echo "Code Found<P>";
}
}
return $codes;
}
The code works with one hiccup. You are creating the code with
$tmp_code = str_random(10);
and I need it to be a 10 digit code. So when I run your code it works fine. When I replace
$tmp_code = str_random(10);
with
$tmp_code = mt_rand(1000000000, 9999999999);
it fails on duplicate key still. Not sure what the difference would be.
The things you are trying to do mt_rand() or str_random() does not generate any kind of unique id that you are expecting.
If you really need any unique id, you can uniqid() use this. However, it wont generate number only.
The meaning of your error is that you are doing another insert with the same combination of columns, which seams to be defined as UNIQUE. If it is so, it doesn't allow to enter same combination (it seems like it consists of two fields) twice.
Thanks I figured it out. The issue was creating a 10 digit code and inserting it into datatype of int. Int has a limit of 2147483647 so basically anything created higher will be inserted at that high limit so it was creating a duplicate. I lowered it to 9 digits and it works fine. I could also make the data type a big int and it would work.