M
M
Mesuti2020-04-21 22:06:20
PHP
Mesuti, 2020-04-21 22:06:20

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

When you add an element to the database, you must assign a unique key to it.
Numeric is not suitable, since you can parse all products with a simple search.

How to make a cycle of checking for uniqueness?
Which will generate a key until there are no duplicates.

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

Unloading a column with keys from the database

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

O8UMzbN4oeNXzJYDNTmbreNvPLZ4PT6ctFyUmMR0

As already suggested, iterating and comparing each element of the array will be resource-intensive with a large amount of data.
Therefore, the best option is to select a specific value from the database.

Unsuccessfully made such code where
$unique is a key. generated with uniqid()
$arrayAllKey - array of existing keys
$findedKey - select cell from database with key
$arrayAllKey[0]["category_key"] - value of found key $findedKey
// Указываю существующий ключ, чтобы цикл нашел дубль
$unique = "5e9dfcc637f75"; 

// Берем значение сгенерированного ключа $unique
// Если найдет значение, то выдаст его, если нет, ничего не выдаст
$findedKey = R::getAll('SELECT `category_key` FROM `items` WHERE `id_user` = ? and `category_key` = ?', [104, $unique]); 

// Если значение найденного ключа есть
if ($findedKey[0]["category_key"]) {
    // делаем генерацию нового ключа
    $unique = uniqid(); 
    // снова выбираем значение из бд
    $findedKey = R::getAll('SELECT `category_key` FROM `items` WHERE `id_user` = ? and `category_key` = ?', [104, $unique]);
} else {
    // если дублей не найдено, выводим уникальный ключ
    echo $unique;
};


ps
Cost only a specific goal. No alternatives.
Generate a key, check for uniqueness compared to unloading from the DB and write to the DB if it is unique..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-04-21
@Rsa97

UUID v4 will save you.
PS But if they want to spar, they will spar. They will simply take a list of products directly from your page. You're going to publish them all somewhere.

F
FanatPHP, 2020-04-21
@FanatPHP

Your goods, if at least someone needs them for a hundred years at lunch, will be paired with numerical, alphabetic, alphanumeric, unique, unrepeatable, imaginary, hidden, secret, encrypted, hidden in any way indexes.
So do not torture your fragile brain, make digital indexes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question