I am working with laravel. I have 1 million data in a database. I am storing as random string. I need to search newly generated Random string so that it won't get repeated.
I am taking all the string in a array from database and searching the newly generated string from php in_array(), but it taking to much time .
suggest me the efficient way to search from array or any other way so that string won't get repeated.
Asked
Active
Viewed 276 times
0
Tomasz Jakub Rup
- 10,502
- 7
- 48
- 49
Vikash
- 219
- 5
- 13
2 Answers
2
Don't take all the strings into array. Just do a query to verify if the next string you want to insert already exists. Something like:
SELECT count(*)
FROM random_strings
WHERE random_string = '$newRandomString';
If this query returns 1 then you can show a message that the random string already exists.
Notes
- You must add an unique index to the
random_stringfield. - The query above is just an example to help you understand the solution. You may use
Eloquentto do the query.
Mihai Matei
- 24,166
- 5
- 32
- 50
-
Its somewhat better but not as per my requirement. when I am inserting the data into the database then after 1300 string it taking 8-10 sec to insert a new string after checking . please tell me some other way which can check and insert data in less time – Vikash Dec 15 '15 at 10:04
0
Make your random string column in the database a UNIQUE KEY.
If a new insert fails with a duplicate key error then retry it with a second random string.
Better yet, read up on UUIDs: How unique is UUID?
Community
- 1
- 1
Peter Dixon-Moses
- 3,169
- 14
- 18