I'm struggling to build 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.
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");
// 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"]);
$email = student_input($_POST["email"]);
$birthday = student_input($_POST["birthday"]);
$phone = student_input($_POST["phone"]);
// validate submission
if (empty($_POST["firstname"]))
{
$errorMsg[] = "First name is required.";
}
else if(empty($_POST["lastname"]))
{
$errorMsg[] = "Last name is required.";
}
else if(empty($_POST["username"]))
{
$errorMsg[] = "Username is required.";
}
else if(!empty($_POST["username"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
{
$errorMsg[] = "Username must contain only letters and numbers.";
}
if (strlen($username) < 4 || strlen($username) > 10)
{
$errorMsg[] = "Username must be from 4 to 10 characters.";
}
}
else if(empty($_POST["gender"]))
{
$errorMsg[] = "Gender is required.";
}
else if(empty($_POST["password"]))
{
$errorMsg[] = "Enter a password.";
}
else if(!empty($_POST["password"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $password))
{
$errorMsg[] = "Password must contain letters, numbers and special characters.";
}
if (strlen($password) < 8 || strlen($password) > 15)
{
$errorMsg[] = "Password must be from 8 to 15 characters.";
}
}
else if (empty($_POST["confirmation"]))
{
$errorMsg[] = "Confirm your password.";
}
else if ($_POST["password"] != $_POST["confirmation"])
{
$errorMsg[] = "Password and confirmation don't match.";
}
else if(empty($_POST["email"]))
{
$errorMsg[] = "Your email address is required.";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$errorMsg[] = "Invalid email format";
}
else if(empty($_POST["birthday"]))
{
$errorMsg[] = "Birthday is required.";
}
else if(!empty($_POST["birthday"]))
{
$birthday = student_input($_POST["birthday"]);
$today = date("d-m-Y");
$diff = date_diff(date_create($birthday), date_create($today));
if($diff->format('%y%') < 6)
{
$errorMsg[] = "You must be at least 6 years old to register.";
}
}
else if(empty($_POST["phone"]))
{
$errorMsg[] = "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))
{
$errorMsg[] = "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))
{
$errorMsg[] = "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))
{
$errorMsg[] = "The telephone number should start with a 0";
}
}
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 "$errorMsg" show then continue
{
$new_password = password_hash($password, PASSWORD_DEFAULT); //encrypt password using password_hash()
// insert form input into database
$result = "INSERT INTO users (firstname, lastname, username, gender, password, email, birthday, phone, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt= $pdo->prepare($result);
$stmt->execute([$firstname, $lastname, $username, $gender, $password, $email, $birthday, $phone, $imagename]);
// if data is in database
if ($stmt->execute([$firstname, $lastname, $username, $gender, $password, $email, $birthday, $phone, $imagename]))
{
// 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 the 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>