I'm trying to create a unique key to save information in the database, but for some reason the $randStr variable has nothing at the end. After submitting, I get only a new id and email, nothing appears in the keystring. What's wrong?
Here's my sql table:
create table users (
id int(11) not null PRIMARY KEY AUTO_INCREMENT,
keystring varchar(110) not null,
email varchar(220) not null
);
php code:
<?php
include_once 'includes/dbh.php';
function checkKeys($conn, $randStr) {
$sqlcheck = "SELECT keystring FROM users";
$result = mysqli_query($conn, $sqlcheck);
while ($row = mysqli_fetch_assoc($result)) {
if ($row['keystring'] == $randStr) {
$keyExists = true;
break;
} else {
$keyExists = false;
}
}
return $keyExists;
}
function generateKey($conn) {
$keyLength = 8;
$str = "0123456789abcdefghijklmnopqrstuvwxyz";
$randStr = substr(str_shuffle($str), 0, $keyLength);
$checkKey = checkKeys($conn, $randStr);
while($checkKey == true) {
$randStr = substr(str_shuffle($str), 0, $keyLength);
$checkKey = checkKeys($conn, $randStr);
}
return $randStr;
}
$recipient = $_POST['emailFor'];
$sender = $_POST['senderEmail'];
$message = $_POST['message'];
$sql = "INSERT INTO users (keystring, email) VALUES('$randStr', '$sender');";
mysqli_query($conn, $sql);