I already googled it, but I just found similar answers.
I'm not a back-end developer, so I don't know a lot of SQL. I need to generate and insert a 6 digit random value that involves numbers and characters (varchar, I think) that doesn't exist in the same column.
I tried this FLOOR(RAND() * 401) + 100
that I found somewhere, but it just generate numbers and... nothing more.
I'm lost.
Please, masters of databases, light my way with your random numbers ;-;
SELECT LPAD(CONV(RAND() * POW(36, 6), 10, 36), 6, 0)
This will create a 6 character "random" alphanumeric value.
But:
Update:
However - because you will need to check, if the value already exists, you better create the number in PHP.
$success = false;
while (!$success) {
$rndInt = rand(0, pow(36, 6) - 1);
$rndStr = base_convert ($rndInt, 10, 36);
$rndStr = str_pad($rndStr , 6, "0", STR_PAD_LEFT);
$query = "SELECT 1 FROM your_table WHERE your_column = {$rndStr} LIMIT 1";
$db->query($query);
if (!$db->fetchColumn()) { // value does not exist yet
// insert new random value
$query = "INSERT INTO your_table (your_column) VALUES ({$rndStr})";
$db->query($query);
$success = true; // will terminate the loop
} else { // value already exists
// do nothing - try again in the next loop
}
}
You will need to ajust the code to what ever you use for MySQL communication.