Ticket System in PHP - #4 Ticket Creation


This tutorial is the fourth part in my series of how to create a PHP based ticket system. This part will be covering inserting the generated ticket/random string in to the 'tickets' table within your database.


We only want to insert a new ticket when a certain event occurs, this event will be when the 'Forgotten Password' link or button is clicked/selected. Are you can see from the previous tutorial, I have the following form to begin the process...
  1. <form action='reset.php' method='GET'>
  2. <input type='text' placeholder='Email address' name='email' />
  3. <input type='submit' value='Send Reset Email' name='emailButton' />
  4. </form>
This means that when the above form is used, the user will enter their email address for their accoutn, and then click the submit button. When they click the submit button, the information 'emailButton' and 'email' will be sent over 'GET' method to the page 'reset.php'. So, on the 'reset.php' page we will type the following code.


First we want to ensure that the email address has been sent...
  1. if (isSet($_GET['emailButton']) && isSet($_GET['email'])) {
  3. }
Next we want to set the form variables to local variables...
  1. $email = $_GET['email'];
We also want to secure the input by sanitising it via the 'strip_tags' PHP function and 'mysqli_real_escape_string' MySQL(i) function. This will add additional security to our website form...
  1. $email = strip_tags($email);
  2. $email = mysqli_real_escape_string($email);
Now that we have the email address, we want to get a new ticket text/ID using our random text string generation function...
  1. $ticket = generateRandom();
To insert this ticket in to the 'tickets' database table, we want to get the email address user account's ID. So first we fetch all records with the entered email address, then get the first ID. If there is no account found, the email doesn't link to an account, and so an error is thrown...
  1. $q = mysqli_query($con, "SELECT * FROM `users` WHERE `email`='$email'");
  2. if ($q && mysqli_num_rows($q) > 0) {
  3. $accountID = mysqli_fetch_array($q)['id'];
  4. }else{
  5. echo 'No account found!';
  6. }
The next thing we want to do is insert the ticket to the 'tickets' database table...
  1. $qq = mysqli_query($con, "INSERT INTO `tickets` VALUES ('', '$email', '$accountID')");
  2. if ($qq) {
  4. }else{
  5. echo 'Unable to create ticket.';
  6. }
Finally, if the ticket has successfully been created, we want to email the entered email address with the ticket...
  1. mail($email, 'Ticket ID', 'Your ticket ID for password reset form is: ' . $ticket);
  2. echo 'Emailed with a ticket!';


Add new comment