I have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp.
I have added another column called 'unique_code' (varchar(64), utf8_unicode_ci).
What I would very much appreciate assistance with is;
a) Generating a 5 digit alphanumeric code, ie: 5ABH6
b) Check all rows the ‘unique_code’ column to ensure it is unique, otherwise re-generate and check again
c) Insert the uniquely generated 5 digit alphanumeric code into 'unique_code' column, corresponding to the email address just entered.
d) display the code on screen.
What code must I put and where?
My current php is as follows:
require "includes/connect.php";
$msg = '';
if($_POST['email']){
// Requested with AJAX:
$ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
try{
if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
throw new Exception('Invalid Email!');
}
$mysqli->query("INSERT INTO coming_soon_emails
SET email='".$mysqli->real_escape_string($_POST['email'])."'");
if($mysqli->affected_rows != 1){
throw new Exception('You are already on the notification list.');
}
if($ajax){
die('{"status":1}');
}
$msg = "Thank you!";
}
catch (Exception $e){
if($ajax){
die(json_encode(array('error'=>$e->getMessage())));
}
$msg = $e->getMessage();
}
}
Hope this helps:
a) I did something very similar to this where I was generating unique codes which were to be used as URLs. I wrote this to generate the codes:
$characters is a string of “allowed” characters. We chose to remove the vowels so that there was no chance of making unwanted words 🙂 You could change this. There are simpler ways to write it but we needed something quite specific.
You would use it like this:
b) For this just wrap your insert statement in a select statement check for that unique code. If the code exists then generate another code and try again. One way you could do this is (NB: this isn’t tested and it may be susceptible to an infinite loop if you happen to get into a situation where you’ve used up all your codes 😉 And you should probably add a check to make sure the INSERT was succesful):
c) To insert the unique code just add this to your insert statement where $unique_code is the variable assigned the return value from the function above:
d) Just echo the variable you assigned the code to e.g: