I've taken this answer from a different question, you can find here. Credit to Stephen Watkins.
So first thing you need to do is create your random generated string...
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString; }
And then a function to write and check the database...
function inputIntoDB(){
$string = generateRandomString();
$db->where('COLUMN NAME',$string)->getOne('TABLENAME');
if (!$db->count > 0){
//insert data into the database.
}
}
Edit: Just to claify what the above code does (or should do).
It generates the 10 character string.
It will then query the database to see if that string exists.
If there is no result (!$db->count >0), then we can assume it's not a duplicate so we can go ahead and insert the string into our database.
Edit2: Here's the code if you're using MySQLi commands:
$link = mysqli_connect("localhost", "user", "password", "db name");
function inputIntoDB(){
$string = generateRandomString();
$query = "SELECT * FROM table WHERE columnName = $string";
if (!$result = $mysqli->query($link,$query)) {
$query = "INSERT INTO table (columnName) VALUES ($string)";
$mysqli->query($link,$query);
} }