How Can I get This PHP Registration Script Using PDO Prepared Statements/Positional Placeholders To Run?
I’m trying to create a PHP registration script using PDO prepared statements with positional placeholders. But the MySQL queries don’t execute. var_dump();
doesn’t display any error.
I desperately need someone to closely look at my code and explain to me why the queries don’t execute.
Below is a rewrite of register.php, which now displays errors, if certain, predefined conditions are not met. However, it doesn’t display any error, when the insert or select query fail. var_dump(); doesn’t display any error either, even though PDO queries fail to execute.
Please, I need your help to fix this. Your time and input are much appreciated in advance. Thanks.
register.php:
<?php // include configuration file require ("includes/config.php"); //Class import for image uploading //classes is the map where the class file is stored (one above the root) include ("classes/upload/upload_class.php"); // define variables and set to empty values $firstnameErr = $lastnameErr = $usernameErr = $genderErr = $passwordErr = $confirmationErr = $emailErr = $birthdayErr = $phoneErr = ""; $firstname = $lastname = $username = $gender = $password = $confirmation = $email = $birthday = $phone = ""; // if form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { $firstname = student_input($_POST["firstname"]); $lastname = student_input($_POST["lastname"]); $username = student_input($_POST["username"]); $gender = student_input($_POST["gender"]); $password = student_input($_POST["password"]); $confirmation = student_input($_POST["confirmation"]); $email = student_input($_POST["email"]); $birthday = student_input($_POST["birthday"]); $phone = student_input($_POST["phone"]); // validate submission if (empty($_POST["firstname"])) { $firstnameErr = "First name is required."; } else { $firstname = student_input($_POST["firstname"]); } if(empty($_POST["lastname"])) { $lastnameErr = "Last name is required."; } else { $lastname = student_input($_POST["lastname"]); } if(empty($_POST["username"])) { $usernameErr = "Username is required."; } else if(!empty($_POST["username"])) { // validate username if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) { $usernameErr = "Username must contain only letters and numbers."; } if (strlen($username) < 4 || strlen($username) > 10) { $usernameErr = "Username must be from 4 to 10 characters."; } } else { $username = student_input($_POST["username"]); } if(empty($_POST["gender"])) { $genderErr = "Gender is required."; } else { $gender = student_input($_POST["gender"]); } if(empty($_POST["password"])) { $passwordErr = "Enter a password."; } else if(!empty($_POST["password"])) { // validate username if (!preg_match("/^[a-zA-Z0-9]*$/", $password)) { $passwordErr = "Password must contain letters, numbers and special characters."; } if (strlen($password) < 8 || strlen($password) > 20) { $passwordErr = "Password must be from 8 to 20 characters."; } } else if (empty($_POST["confirmation"])) { $confirmationErr = "Confirm your password."; } else if ($_POST["password"] != $_POST["confirmation"]) { $confirmationErr = "Password and confirmation don't match."; } else { $password = student_input($_POST["password"]); } if(empty($_POST["email"])) { $emailErr = "Your email address is required."; } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } else { $email = student_input($_POST["email"]); } if(empty($_POST["birthday"])) { $birthdayErr = "Birthday is required."; } else if(!empty($_POST["birthday"])) { $today = date("d-m-Y"); $diff = date_diff(date_create($birthday), date_create($today)); if($diff->format('%y%') < 6) { $birthdayErr = "You must be at least 6 years old to register."; } else { $birthday = student_input($_POST["birthday"]); } } if(empty($_POST["phone"])) { $phoneErr = "Phone number is required."; } else if(!empty($_POST["phone"])) { // Don't allow country codes to be included (assumes a leading "+") if (preg_match('/^(\+)[\s]*(.*)$/',$phone)) { $phoneErr = "You should not include the country code."; } // Remove hyphens - they are not part of a telephone number $phone = str_replace ('-', '', $phone); // Now check that all the characters are digits if (!preg_match('/^[0-9]{10,11}$/',$phone)) { $phoneErr = "Phone number should be either 10 or 11 digits"; } // Now check that the first digit is 0 if (!preg_match('/^0[0-9]{9,10}$/',$phone)) { $phoneErr = "The telephone number should start with a 0"; } else { $phone = student_input($_POST["phone"]); } } else if(!empty($_FILES["userimage"])) { //This is the directory where images will be saved $max_size = 1024*250; // the max. size for uploading $my_upload = new file_upload; $my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder) $my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here // $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!) $my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100) $my_upload->rename_file = false; $my_upload->the_temp_file = $_FILES['userimage']['tmp_name']; $my_upload->the_file = $_FILES['userimage']['name']; $my_upload->http_error = $_FILES['userimage']['error']; $my_upload->replace = "y"; $my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file { $full_path = $my_upload->upload_dir.$my_upload->file_copy; $imagename = $my_upload->file_copy; } else { $imagename = ""; } } else { try { $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute(student_input($_POST["username"])); $user = $stmt->fetch(); # get users data if($user["username"]==$username) { $errorMsg[]="Sorry username already exists"; //check condition username already exists } else if($user["email"]==$email) { $errorMsg[]="Sorry email already exists"; //check condition email already exists } else if($user["phone"]==$phone) { $errorMsg[]="Sorry, the phone number already exists"; //check condition email already exists } else if(!isset($errorMsg)) //check no "$errorMs g" show then continue { $new_password = password_hash($password, PASSWORD_DEFAULT); //encrypt password using password_hash() // insert form input into database $stmt= $pdo->prepare("INSERT INTO users (firstname, lastname, username, gender, password, email, birthday, phone, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")->execute($data); // find out user's ID $stmt = $pdo->query("SELECT LAST_INSERT_ID() AS user_id"); $user_id = $stmt[0]["user_id"]; // redirect to list users page header("Location: userinfo.php"); } } catch(PDOException $e) { echo $e->getMessage(); } } } // render the header template include("templates/header.php"); // render add user template include("templates/register-form.php"); // render the footer template include("templates/footer.php"); ?>
I have the following, relevant code in functions.php, which is called by the config.php:
// validate user input function student_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }
Another thing: how do I print the errors on the register-form.php right below any existing error’s input field?
register-form.php:
<br> <br> <h1>Register</h1> <br> <form enctype="multipart/form-data" action="register.php" method="post"> <fieldset> <div class="form-group"> <label>First Name:</label><span class ="error">*</span> <input autofocus class="form-control" name="firstname" placeholder="First Name" type="text"/> <span class = "error"><?php //echo $errorMsg["firstname"];?></span> </div> <div class="form-group"> <label>Last Name:</label><span class ="error">*</span> <input class="form-control" name="lastname" placeholder="Last Name" type="text"/><br /> <span class = "error"><?php //echo $errorMsg["lastname"];?></span> </div> <div class="form-group"> <label>Username:</label><span class ="error">*</span> <input class="form-control" name="username" type="text"/><br /> <span class = "error"><?php //echo $errorMsg["username"];?></span> </div> <div class="form-group"> <label>Gender:</label><span class ="error">*</span> <select class="form-control" name="gender" value="gender"> <option value="">Select your gender</option> <option value="Male">Male</option> <option value="Female">Female</option> </select><br /> <span class = "error"><?php //echo $error;?></span> </div> <div class="form-group"> <label>Password:</label><span class ="error">*</span> <input class="form-control" name="password" type="password"/ autocomplete="off"><br /> <span class = "error"><?php //echo $error;?></span> </div> <div class="form-group"> <label>Confirm Password:</label><span class ="error">*</span> <input class="form-control" name="confirmation" type="password"/><br /> <span class = "error"><?php //echo $error;?></span> </div> <div class="form-group"> <label>Email:</label><span class ="error">*</span> <input class="form-control" name="email" placeholder="Email" type="text"/><br /> <span class = "error"><?php //echo $error;?></span> </div> <div class="form-group"> <label>Phone:</label><span class ="error">*</span> <input class="form-control" name="phone" placeholder="Phone" type="tel" min="10" max="11"/><br /> <span class = "error"><?php //echo $error;?></span> </div> <div class="form-group"> <label>Date of Birth:</label><span class ="error"></span> <input class="form-control" name="birthday" placeholder="birthday" type="date" /><br /> <span class = "error"><?php //echo $error[birthday];?></span> </div> <div class="form-group"> <label>Passport Photo:</label><input class="form-control" name="userimage" id="fileimage" placeholder="Your Photo" type="file"/> </div> <div class="form-group"> <button type="submit" class="btn btn-default" name="Register" value="Register">Register</button> </div> </fieldset> </form> <div> or <a href="login.php">Login</a> </div> <br/> <br> <br>