How do I choose a unique value in relation to an array unloaded from the database?

35 views Asked by At

When adding an item to the database, you must assign a unique key to it.
Numeric is not suitable, since can parse simply iterate over all the products.

How do I do a unique verification cycle correctly?
Which will generate the key until there are no duplicates.

uniqid(); generates the appropriate keys, but does not guarantee the uniqueness of the value, so I decided to check with the existing keys.

Downloading a column with keys from the database

$arrayAllKey = R::getAll('SELECT `category_key` FROM `items` WHERE `id_user` = 104);

enter image description here

Searching and comparing each element of the array will be expensive if there is a large amount of data.

Therefore, the best option is to select a specific value from the database.

Unsuccessfully made a code where:
$unique - key generated using uniqid()
$arrayAllKey - array of existing keys
$findedKey- selecting a cell from a database with a key
$arr[0]["category_key"] - value of the found key $findedKey

// writing the key that is in the database
$unique = "5e9dfcc637f75"; 

// Taking the value of the generated key $unique
// If it finds a value, it will output it; if it doesn't, it won't output anything
$findedKey = R::getAll('SELECT `category_key` FROM `items` WHERE `id_user` = ? and `category_key` = ?', [104, $unique]); 

// If the value of the found key is present
if ($findedKey[0]["category_key"]) {
    // generating a new key
    $unique = uniqid(); 
    // selecting the value from the database again
    $findedKey = R::getAll('SELECT `category_key` FROM `items` WHERE `id_user` = ? and `category_key` = ?', [104, $unique]);
} else {
    // if no duplicates are found, output a unique key
    echo $unique;
};
0

There are 0 answers