Phpmailer sends mail with form errors - php

I have searched the internet for many hours. My Phpmailer works great but, it sends the email even if the form has errors, like if the email is take. I can't get it to know if the form has errors. Do I need to also query the database in my Phpmailer file or can I use the query return already done in my PHP register query?
In my register PHP query I check for if email is taken. If the email is taken the form displays an error, but PHPmailer sends the email even with the email taken error. How can I stop PHPmailer form sending an email with form errors.
Notice my variable $user holds the check if email is taken return. How can I get PHPmailer to also use the variable $user?
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
if(array_key_exists("first",$_POST) && $_POST["first"] != "" && array_key_exists("last",$_POST) && $_POST["last"] != "" && (array_key_exists('email', $_POST) and PHPMailer::validateAddress($_POST['email'])) && array_key_exists("unit",$_POST) && $_POST["unit"] != "") {
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'gator*****hostgator.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '***********.com'; // SMTP username
$mail->Password = '*********'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('admin********.com', 'Admin');
$mail->addAddress('admin*****.com', 'HP Website'); // Add a recipient
$mail->addAddress($_POST['email']); // Name is optional
// $mail->addReplyTo($email);
// $mail->addCC($_REQUEST['email']);
// $mail->addBCC('bcc#example.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$unit = $_POST['unit'];
$bed = $_REQUEST['bed'];
$bath = $_REQUEST['bath'];
$web = $_REQUEST['web'];
$phone = $_REQUEST['phone'];
$manage = $_REQUEST['manage'];
//$unit = $_REQUEST['unit'];
//$uid = $_REQUEST['uid'];
$ck = $_REQUEST['rent'];
//Content
$mail->addEmbeddedImage('img/logo4.png', 'logo');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Your HP unit is signed up';
// $first_name = $_POST['first_name'];
// $last_name = $_POST['last_name'];
// $license_type = $_POST['license_type'];
$mail->Body = '<p style="background-color:#333; color:orange; text-align:center; font-weight:bolder">Welcome to the HP Owner website</p>
<p style="text-align:center; margin:0"><img src="cid:logo"></p>
<p><strong>Name: </strong>'.$first.' '.$last.'</p>
<p><strong>Email: </strong>'.$email.'</p>
<p><strong>Unit#: </strong>'.$unit.'</p>
<p><strong>Bed: </strong>'.$bed.'</p>
<p><strong>Bath: </strong>'.$bath.'</p>
<p><strong>Website: </strong>'.$web.'</p>
<p><strong>Phone: </strong>'.$phone.'</p>
<p><strong>Management: </strong>'.$manage.'</p>
<p><strong>Show on HP website - (1 means show): </strong>'.$ck.'</p>
<p>If any of your info above is wrong, login with your username and password. Click on Update My Unit button and update your info..<br>
<br>If you checked the box Show On Rental Site, your unit will show - refresh the rental site or go to http://www.*********.php<br>
<br>If you need to delete everything and start over - contact the admin email admin***********.com';
$mail->AltBody = 'HP Owner Web Site - You are signed up';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
?>
AND MY PHP query
require_once 'dbh.inc.php';
//include_once 'mailer0.php';
include_once 'includes/mailer.php';
// Init vars
$first = $last = $email = $unit = $bed = $bath = $web = $phone = $manage = $pwd = $confirm_password = $ck = '';
$name_err = $unit_err = $bed_err = $bath_err = $phone_err = $email_err = $password_err = $confirm_password_err = '';
// Process form when post submit
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Sanitize POST
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
// Put post vars in regular vars
$first = trim($_POST['first']);
$last = trim($_POST['last']);
$email = trim($_POST['email']);
$unit = trim($_POST['unit']);
$bed = trim($_POST['bed']);
$bath = trim($_POST['bath']);
$web = trim($_POST['web']);
$phone = trim($_POST['phone']);
$manage = trim($_POST['manage']);
// $uid = trim($_POST['uid']);
$pwd = trim($_POST['pwd']);
$confirm_password = trim($_POST['confirm_password']);
$ck = trim($_POST['rent']);
// Validate email
if(empty($email)){
$email_err = 'Please enter email';
} else {
$stmt = $pdo->prepare("SELECT * FROM condos_hp WHERE user_email=?");
if($stmt->execute([$email]));{
$user = $stmt->fetch();
}
if ($user) {
// email found
$email_err = 'Email is already taken';
}
unset($stmt);
}
// Validate name
if(empty($first) || empty($last)){
$name_err = 'Please enter name';
}
// Validate name
if(empty($unit)){
$unit_err = 'Please enter your unit #';
}
// Validate name
if(empty($bed) || empty($bath)){
$bed_err = 'Please enter bed/bath #';
}
// Validate name
if(empty($phone)){
$phone_err = 'Please enter your phone';
}
// Validate password
if(empty($pwd)){
$password_err = 'Please enter password';
} elseif(strlen($pwd) < 6){
$password_err = 'Password must be at least 6 characters ';
}
// Validate Confirm password
if(empty($confirm_password)){
$confirm_password_err = 'Please confirm password';
} else {
if($pwd !== $confirm_password){
$confirm_password_err = 'Passwords do not match';
}
}
// Make sure errors are empty
if(empty($name_err) && empty($email_err) && empty($password_err) && empty($confirm_password_err)){
// Hash password
$pwd = password_hash($pwd, PASSWORD_DEFAULT);
// Prepare insert query
// (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, rent)
$sql = 'INSERT INTO condos_hp (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, user_pwd, rent) VALUES (:first, :last, :email, :unit, :bed, :bath, :web, :phone, :manage, :pwd, :rent)';
// $sql = 'INSERT INTO condos_hp (name, email, password) VALUES (:name, :email, :password)';
if($stmt = $pdo->prepare($sql)){
// Bind params
// $stmt->bindParam(':name', $name, PDO::PARAM_STR);
// $stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':unit', $unit, PDO::PARAM_STR);
$stmt->bindParam(':bed', $bed, PDO::PARAM_STR);
$stmt->bindParam(':bath', $bath, PDO::PARAM_STR);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
// $stmt->bindParam(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_STR);
// $stmt->bindParam(':id', $id);
// Attempt to execute
if($stmt->execute()){
// Redirect to login
header('Location: login0.php');
} else {
die('Something is not right');
}
}
unset($stmt);
}
// Close connection
unset($pdo);
}
?>
UPDATED CURRENT CODE.......
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Include db config
require_once 'dbh.inc.php';
//include_once 'mailer0.php';
// Init vars
$first = $last = $email = $unit = $bed = $bath = $web = $phone = $manage = $uid = $pwd = $confirm_password = $ck = '';
//$name_err = $unit_err = $bed_err = $bath_err = $phone_err = $email_err = $uid_err = $password_err = $confirm_password_err = '';
//$error = isset($_SESSION['error']) ? $_SESSION['error'] : [];
// Process form when post submit
if (isset($_POST["register"])) {
// $error = array()
//($_SERVER['REQUEST_METHOD'] === 'POST'){
// echo var_dump($_POST);
// echo '<br/>';
// print_r($_POST);
//$error = ($_SESSION['error']);
// Sanitize POST
// $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$error = array();
var_dump($error);
if (!empty($error)) {
echo "not empty";
} else {
echo "empty";
}
// Put post vars in regular vars
$first = trim($_POST['first']);
$last = trim($_POST['last']);
$email = trim($_POST['email']);
$unit = trim($_POST['unit']);
$bed = trim($_POST['bed']);
$bath = trim($_POST['bath']);
$web = trim($_POST['web']);
$phone = trim($_POST['phone']);
$manage = trim($_POST['manage']);
$uid = trim($_POST['uid']);
$pwd = trim($_POST['pwd']);
$confirm_password = trim($_POST['confirm_password']);
$ck = ($_POST['rent']);
// Validate email
if (empty($email)) {
$error['email'] = "Please enter email";
} else {
// check if email is taken
/*$sql = 'SELECT * FROM condos_hp WHERE user_email = :email';
if($stmt = $pdo->prepare($sql)){
// Bind variables
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
// Attempt to execute
if($stmt->execute()){
// Check if email exists
$user = $stmt->fetch()
if ($user){
$email_err = 'Email is already taken';
}
} else {
die('Something went wrong');
}
}*/
/*$sql= "SELECT * FROM condos_hp WHERE uid = :uid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':uid', $uid);
//$stmt = $pdo->prepare("SELECT uid FROM condos_hp WHERE uid=:uid");
//$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
//$user = $stmt->fetchALL(PDO::FETCH_ASSOC);
//print_r($stmt->fetchObject())
//$stmt->setFetchMode(PDO::FETCH_ASSOC);
$user = $stmt->fetch();
if ($user) {
// email found
$uid_err = 'UserID is already taken';
echo var_dump($user);*/
$stmt = $pdo->prepare("SELECT uid FROM condos_hp WHERE uid=?");
$stmt->bindValue('1', $uid);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// $error[] = 'sorry username already taken !';
// email found
$error['uid'] = "user ID already taken";
// die;
// header('Location: register.php');
print_r($user);
// print_r($error);
//} else { // or not die('Something went wrong'); }
} else {
// echo 'user does not exist<br>';
}
unset($stmt);
}
// Validate name
if (empty($first) || empty($last)) {
$error['name'] = "Enter name";
}
// Validate name
if (empty($unit)) {
$error['unit'] = 'Please enter your unit #';
}
// Validate name
if (empty($bed) || empty($bath)) {
$error['rooms'] = 'Please enter bed/bath #';
}
// Validate name
if (empty($phone)) {
$error['phone'] = 'Please enter your phone';
}
//Check phone # format 000-000-0000
if (!preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {
$error['phone'] = 'Please enter correct phone format';
}
//Check manage format
if (!preg_match("/^(\s\(([^)]+)\))?[[:punct:]]?\p{Lu}+(?:[\s'-]?[\p{L}\d]+)+(\(([^)]+)\))*$/", $manage)) {
$error['manage'] = 'Please enter correct management format';
}
//Check password format 4 and 8 digits long and include at least one numeric digit.
// if (!preg_match("/^(?=.*\d).{4,8}$/", $pwd)) {
// $password_err = 'Password must be at least 4 digits with 1 number ';
if (empty($uid)) {
$error['uid'] = 'Please enter uid';
}
// Validate password
if (empty($pwd)) {
$error['pwd'] = 'Please enter password';
}
if (!preg_match("/^(?=.*\d).{4,8}$/", $pwd)) {
$error['pwd'] = 'Password must be at least 4 digits with 1 number ';
}
// Validate Confirm password
if (empty($confirm_password)) {
$error['pwdpar'] = 'Please confirm password';
} else {
if ($pwd !== $confirm_password) {
$error['pwdpar'] = 'Passwords do not match';
}
}
// Make sure errors are empty
if (empty($error)) {
// Hash password
$pwd = password_hash($pwd, PASSWORD_DEFAULT);
// Prepare insert query
// (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, rent)
$sql = 'INSERT INTO condos_hp (user_firstname, user_lastname, user_email, user_unit, user_bed, user_bath, user_web, user_phone, user_manage, uid, user_pwd, rent) VALUES (:first, :last, :email, :unit, :bed, :bath, :web, :phone, :manage, :uid, :pwd, :rent)';
// $sql = 'INSERT INTO condos_hp (name, email, password) VALUES (:name, :email, :password)';
if ($stmt = $pdo->prepare($sql)) {
// Bind params
// $stmt->bindParam(':name', $name, PDO::PARAM_STR);
// $stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':unit', $unit, PDO::PARAM_STR);
$stmt->bindParam(':bed', $bed, PDO::PARAM_STR);
$stmt->bindParam(':bath', $bath, PDO::PARAM_STR);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
$stmt->bindParam(':uid', $uid, PDO::PARAM_STR);
$stmt->bindParam(':pwd', $pwd, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_STR);
// $stmt->bindParam(':id', $id);
// Attempt to execute
if ($stmt->execute()) {
// Redirect to login
header('Location: register.php');
} else {
die('Something is not right');
}
}
unset($stmt);
}
// Close connection
unset($pdo);
}
//include_once 'includes/mailer.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="includes/style.css">
<title>Register HP Account</title>
<script>
function validate(form) {
fail = validateFirst(form.first.value)
fail += validateLast(form.last.value)
fail += validateEmail(form.email.value)
fail += validateUnit(form.unit.value)
fail += validateBed(form.bed.value)
fail += validateBath(form.bath.value)
fail += validateWebsite(form.web.value)
fail += validatePhone(form.phone.value)
fail += validateManage(form.manage.value)
fail += validateUid(form.uid.value)
fail += validatePassword(form.pwd.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
</script>
<script src="includes/validate_functions.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-8 mx-auto">
<h2 style="text-align:center">HP Sign-Up Form</h2>
<p style="text-align:center">Fill in this form to register</p>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<label for="first">First Name</label>
<input type="text" name="first"
class="form-control form-control-lg <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($first); ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
<div class="form-group col-md-4">
<label for="last">Last Name</label>
<input type="text" name="last"
class="form-control form-control-lg <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($last); ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-6">
<label for="email">Email Address</label>
<input type="email" name="email"
class="form-control form-control-lg <?php echo (!empty($error['email'])) ? 'is-invalid' : ''; ?>"
value="<?php echo $email; ?>">
<span class="invalid-feedback"><?php echo $error['email']; ?></span>
</div>
<div class="form-group col-md-2">
<label for="unit">Unit #</label>
<input type="text" name="unit"
class="form-control form-control-lg <?php echo (!empty($error['unit'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($unit); ?>">
<span class="invalid-feedback"><?php echo $error['unit']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-1">
<label for="bed">Bed</label>
<input type="text" name="bed"
class="form-control form-control-lg <?php echo (!empty($error['rooms'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($bed); ?>">
<span class="invalid-feedback"><?php echo $error['rooms']; ?></span>
</div>
<div class="form-group col-md-1">
<label for="bath">Bath</label>
<input type="text" name="bath"
class="form-control form-control-lg <?php echo (!empty($error['rooms'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($bath); ?>">
<span class="invalid-feedback"><?php echo $error['rooms']; ?></span>
</div>
<div class="form-group col-md-6">
<label for="web">Website</label>
<input type="text" name="web" class="form-control form-control-lg"
value="<?php echo htmlentities($web); ?>">
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-3">
<label for="phone">Phone - 000-000-0000</label>
<input type="text" id="yourphone2" name="phone" placeholder="123-456-7890"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
class="form-control form-control-lg <?php echo (!empty($error['phone'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($phone); ?>">
<span class="invalid-feedback"><?php echo $error['phone']; ?></span>
</div>
<div class="form-group col-md-5">
<label for="manage">Management - (VRBO, SELF, etc.)</label>
<input type="text" name="manage"
class="form-control form-control-lg <?php echo (!empty($error['manage'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($manage); ?>">
<span class="invalid-feedback"><?php echo $error['manage'] = 'Please management'; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-2">
<label for="uid">UserID - 8 length</label>
<input type="text" name="uid"
class="form-control form-control-lg <?php echo (!empty($error['uid'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($uid); ?>" placeholder="6 chars ex.betty12">
<span class="invalid-feedback"><?php echo $error['uid']; ?></span>
</div>
<div class="form-group col-md-3">
<label for="pwd">Password - min 6 digits</label>
<input type="password" name="pwd"
class="form-control form-control-lg <?php echo (!empty($error['pwd'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($pwd); ?>"
placeholder="6 to 8 digits include 1 num - ex.1234, absd12">
<span class="invalid-feedback"><?php echo $error['pwd']; ?></span>
</div>
<div class="form-group col-md-3">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password"
class="form-control form-control-lg <?php echo (!empty($error['pwdpar'])) ? 'is-invalid' : ''; ?>"
value="<?php echo htmlentities($confirm_password); ?>">
<span class="invalid-feedback"><?php echo $error['pwdpar']; ?></span>
</div>
</div>
<div class="form-row justify-content-center">
<div class="custom-control custom-checkbox">
<input type="hidden" name="rent" value="0">
<input type="checkbox" value="1" name="rent" class="custom-control-input" id="customCheck1"
checked="checked">
<label class="custom-control-label" for="customCheck1">Check to show on the rental site</label>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<input type="submit" value="register" name="register" class="btn btn-success btn-block">
</div>
<div class="form-group col-md-4">
Have an account? Login
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"
integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="dist/jquery-input-mask-phone-number.js"></script>
<script>
//xxx-xxx-xxxx format code
$(document).ready(function () {
$('#yourphone2').usPhoneFormat({
format: 'xxx-xxx-xxxx',
});
});
</script>
<?php require_once './includes/footer.php'; ?>
</html>

Related

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 Login
</div>
<br/>
<br>
<br>

values added as blank spaces php sql

<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $fullname = $password = $age = $phonenumber = $role = $email = "";
$username_err = $fullname_err = $password_err = $age_err = $phonenumber_err =
$role_err = $email_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
if(var_dump($_POST["username"]))
{
$input_name = trim($_POST["username"]);
if(empty($input_name)){
$username_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$username_err = "Please enter a valid name.";
} else{
$username = $input_name;
}
}
// Validate fullname
if(var_dump($_POST["username"]))
{
$input_fname = trim($_POST["fullname"]);
if(empty($input_fname)){
$fullname_err = "Please enter a name.";
} elseif(!filter_var($input_fname, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$fullname_err = "Please enter a valid name.";
} else{
$fullname = $input_fname;
}
}
// Validate age
if(var_dump($_POST["age"]))
{
$input_age = trim($_POST["age"]);
if(empty($input_age)){
$age_err = "Please enter your age.";
} else{
$age = $input_age;
}
}
// Validate phonenumber
if(var_dump($_POST["phonenumber"]))
{
$input_phonenumber = trim($_POST["phonenumber"]);
if(empty($input_phonenumber)){
$phonenumber_err = "Please enter a proper phonenumber.";
} else{
$phonenumber = $input_phonenumber;
}
}
// Validate role
if(var_dump($_POST["role"]))
{
$input_role = trim($_POST["role"]);
if(empty($input_role)){
$role_err = "Please enter a proper role.";
} else{
$role = $input_role;
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($fullname_err) && empty($age_err) &&
empty($phonenumber_err) && empty($role_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (user_name, full_name, age, phone_number,
role) VALUES (?, ?, ?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssiis", $param_username,
$param_fullname, $param_age, $param_phonenumber, $param_role);
// Set parameters
$param_username = $username;
$param_fullname = $fullname;
$param_age = $age;
$param_phonenumber = $phonenumber;
$param_roll = $roll;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records created successfully. Redirect to landing page";
// Records created successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>ADD NEW USERS</h2>
</div>
<p>Please fill this form to start trading.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err;?></span>
</div>
<div class="form-group <?php echo (!empty($fullname_err)) ? 'has-error' : ''; ?>">
<label>FULL NAME</label>
<input type="text" name="fullname" class="form-control" value="<?php echo $fullname; ?>">
<span class="help-block"><?php echo $fullname_err;?></span>
</div>
<div class="form-group <?php echo (!empty($age_err)) ? 'has-error' : ''; ?>">
<label>AGE</label>
<input type="number" name="age" class="form-control" value="<?php echo $age; ?>">
<span class="help-block"><?php echo $age_err;?></span>
</div>
<div class="form-group <?php echo (!empty($phonenumber_err)) ? 'has-error' : ''; ?>">
<label>PHONENUMBER</label>
<input type="number" name="phonenumber" class="form-control" value="<?php echo $phonenumber; ?>">
<span class="help-block"><?php echo $phonenumber_err;?></span>
</div>
<div class="form-group <?php echo (!empty($role_err)) ? 'has-error' : ''; ?>">
<label>ROLE </label>
<form action="" method="post">
<input type="radio" name="radio" value="<php echo $role; ?>">INVESTOR
<input type="radio" name="radio" value="<php echo $role; ?>">MANAGER
<span class="help-block"><?php echo $role_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
THERE ARE NO ERRORS HOWEVER A BLANK ROW GETS ADDED EVERY TIME I SUBMIT
table in the database is as follows
user_id
user_name
user_password
full_name
age
phone_number
email
role
I am using php 7.2 and sql from phpmyadmin server is running on xampp
Tried using only Trim without isset that gave an undefined index error for all parameters
Your main issue:
In your form every input has the name="name".
It should be "username", "fullname", "phonenumber",..
This is why you receive no values in $_POST['username'].
So why don't you get any error? Because you don't set one if isset($_POST['username']) is false:
if(isset($_POST["username"]))
{
$input_name = trim($_POST["username"]);
if(empty($input_name)){
$username_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$username_err = "Please enter a valid name.";
} else{
$username = $input_name;
}
}
// NO ELSE here. here you should set $fullname_err
Consequently on INSERT you bind to the original initialized value of $username, which is "".

Fatal error: Uncaught PDOException:PDO There is no active transaction in /home/qndt0n0hz1u8/public_html/register.php:185 Stack trace

I am new to server mysql database, i just hosted my server with godaddy, connected to the database, my select query is working fine. After several trouble shooting i decided to use pdo transactions but am getting this error
My php registration script for insertion into database which is not working is show below:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require_once('dbh.php');
require_once'config.php';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['f_name']) && isset($_POST['u_name']) && ($_POST['f_name']) !="" && ($_POST['u_name']) !="" && ($_POST['Email']) !="" && ($_POST['phonenumber']) !="" ) {
/* id should be an auto-increment field in the db */
$f_name = isset($_POST['f_name']) ? $_POST['f_name'] : false;
$u_name = isset($_POST['u_name']) ? $_POST['u_name'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$password1 = isset($_POST['password1']) ? $_POST['password1'] : false;
$Email = isset($_POST['Email']) ? $_POST['Email'] : false;
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : false;
$sponsor = isset($_GET['sponsor']) ? $_GET['sponsor'] : false;
echo $sponsor;
$error_fname = "";
$eror_fname = "";
$errror_fname = "";
$eror_uname = "";
$errror_uname = "";
$error_uname = "";
$eror_password = "";
$errror_password = "";
$error_password = "";
$eror_email = "";
$error_email = "";
$errror_email = "";
$eror_phonenumber = "";
$error_phonenumber = "";
$errror_phonenumber = "";
$error_captcha = "";
$error_sponsor = "";
$errorSmt = "";
if(isset($_POST['f_name']) && isset($_POST['u_name']) && isset(($_POST['Email'])) && isset($_POST['phonenumber']) ) {
$errror_fname = $f_name.' is OK';
//check for duplicate username
$con= new PDO("mysql:host=$serverhost;dbname=silverhub;" , $serverusername, $serverpassword);
$query = $con->prepare("SELECT userid FROM users WHERE u_name=? LIMIT 1");
$u_Check = $query->bindParam(1, $u_name, PDO::PARAM_STR);
$u_Check = $query->execute();
$u_Check = $query->rowCount();
if( $u_Check=$query->rowCount() > 0) {
$eror_uname = ' Sorry'.$u_name.' already taken, please choose another';
}else{
$errror_uname = $u_name.' is OK';
}
//check for duplicate referral
$query = $con->prepare("SELECT sponsor FROM users WHERE userid=? LIMIT 1");
$s_Check = $query->bindParam(1, $userid, PDO::PARAM_INT);
$s_Check = $query->execute();
$s_Check= $query ->fetch(PDO::FETCH_ASSOC);
if( $s_Check['sponsor'] == $u_name) {
$error_sponsor = 'Sorry, user cannot refer himself';
}
//check referral Email
$query = $con->prepare("SELECT userid FROM users WHERE Email=? LIMIT 1");
$e_Check = $query->bindParam(1, $Email, PDO::PARAM_STR);
$e_Check = $query->execute();
$e_Check = $query->rowCount();
if( $p_Check=$query->rowCount() > 0) {
$eror_email = $Email.' already taken, please choose another';
}else{
$errror_email = $Email. ' is OK';
}
//check for duplicate phonenumber
$query = $con->prepare("SELECT userid FROM users WHERE phonenumber=? LIMIT 1");
$p_Check = $query->bindParam(1, $phonenumber, PDO::PARAM_STR);
$p_Check = $query->execute();
$p_Check = $query->rowCount();
if( $al_Check=$query->rowCount() > 0) {
$eror_phonenumber = $phonenumber.' already taken, please choose another';
}else{
$errror_phonenumber = $phonenumber. ' is OK';
}
}
// if(!preg_match("/^[a-zA-Z0-9]*$/",$f_name) && strip_tags(trim($f_name))) {
// $error_fname = 'invalid, fullname must be alphanumerics with no whitespace';
// echo 'invalid, fullname must be alphanumerics with no whitespace';
// }
if(!preg_match("/^[a-zA-Z0-9]*$/",$u_name) && strip_tags(trim($u_name))) {
$error_uname = 'invalid, username must be alphanumerics with no whitespace';
}
if(strlen($u_name) < 3 || strlen($u_name) > 16) {
$error_uname = 'Username must be between 3 - 16 characters';
}
if($password !== $password1) {
$error_password = 'Password and RepeatPassword do not match';
}
if(strlen($password) < 5) {
$error_password = 'Weak password, Password must be more than 5 characters';
}
if(strlen($phonenumber) > 11 && trim(htmlentities($phonenumber))) {
$error_phonenumber = 'Phonenumbers must be an 11 digit number';
}
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$error_email = ' invalid email address, please verify your email address';
}
if(!preg_match("/^[a-zA-Z0-9]*$/",$sponsor) && strip_tags(trim($sponsor))) {
$error_sponsor = 'invalid sponsor name, must be alphanumeric ';
}
if(empty($_POST['recaptcha'])) {
$error_captcha = 'Enter the Verification Code Above';
}
elseif($_POST['recaptcha'] != $_SESSION['recaptcha']) {
$error_captcha = 'Verification Code did not match, try again';
}elseif($_POST['recaptcha'] == $_SESSION['recaptcha']) {
$error_captcha = 'Verification Matched, Click Register';
}
if($u_name && $eror_fname =="" && $error_fname =="" && $errror_fname !=="" && $eror_uname =="" && $error_uname =="" && $errror_uname !=="" && $error_password =="" && $eror_email == "" && $error_email == "" && $errror_email !== "" && $eror_phonenumber =="" && $error_phonenumber =="" && $errror_phonenumber !=="" ) {
class reg extends dbh {
public function userCheck($f_name, $u_name,$password,$Email,$phonenumber,$sponsor) {
try {
$con = new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$con->beginTransaction();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$passenc = password_hash($password, PASSWORD_DEFAULT, array('cost'=>11));
$emailCode = rand().$phonenumber;
$smsCode = rand().$u_name;
$Active = 0;
$Has_reserved_person = 'NO';
$MainTime = time();
$con= new PDO("mysql:host=$this->serverhost;dbname=silverhub;", $this->serverusername, $this->serverpassword);
$sql = "INSERT INTO users (f_name,u_name,password,Email,emailCode,phonenumber,smsCode,sponsor,Active,Has_reserved_person,MainTime) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
$insert = $con->prepare($sql);
$insert->bindParam(1,$f_name,PDO::PARAM_STR);
$insert->bindParam(2,$u_name,PDO::PARAM_STR);
$insert->bindParam(3,$passenc );
$insert->bindParam(4,$Email,PDO::PARAM_STR);
$insert->bindParam(5,$emailCode,PDO::PARAM_STR);
$insert->bindParam(6,$phonenumber,PDO::PARAM_STR);
$insert->bindParam(7,$smsCode,PDO::PARAM_STR);
$insert->bindParam(8,$sponsor,PDO::PARAM_STR);
$insert->bindParam(9,$Active);
$insert->bindParam(10,$Has_reserved_person);
$insert->bindParam(11,$MainTime);
$insert->execute();
$con->commit();
if($insert->execute()){
echo 'insert successfull';
}else{
echo "Execute query error, because:" . print_r($con->errorinfo());
return false;
}
} catch (PDOException $e){
throw $e;
}
}
}
$object = new reg();
$object->userCheck( $f_name, $u_name, $password, $Email, $phonenumber, $sponsor);
}
}
?>
Here is my HTML FORM input:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html !doctype>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="container">
<div id="sec">REGISTER WITH US</div>
<img src="images/images(33).jpg">
<form action='register.php' method='POST' class='ajax-reg'>
<!-- HOW does a user enter a value here if it is HIDDEN??? Removed `required` attribute -->
<div class='form-group'>
<p> Note!!! Fields with astericks must be filled</p>
<input type='hidden' class='form-control' name='userid' placeholder='enter your id' />
</div>
<br>
<div class='form-group'>
<label>fullname*</label>
<input type="text" class="form-control" onblur ="fnamecheck()" id="f_name" name="f_name" placeholder="Enter your fullname" value="<?php echo #$_POST['f_name']?>" /><span id ="fullnameStatus"></span>
</div>
<br>
<div class='form-group'>
<label>username*</label>
<input type="username" class="form-control" name="u_name" id ="u_name" onblur ="usernamecheck()" placeholder="Enter your username" value="<?php echo #$_POST['u_name']?>" /><span id ="usernameStatus"></span>
</div>
<br>
<div class='form-group' >
<label>password*</label>
<input type="password" class="form-control" name="password" id="password" onblur ="passcheck()" placeholder="type in your password" />
</div>
<br>
<div class='form-group' >
<label>RepeatPassword*</label>
<input type="password" class="form-control" name="password1" id ="password1" onblur ="passcheck()" placeholder= "Retype in your password" /><span id ="passwordStatus"></span>
</div>
<br>
<div class='form-group'>
<label>email*</label>
<input type="email" class="form-control" name="Email" id ="Email" onblur ="emailcheck()" placeholder="Enter your email" value="<?php echo #$_POST['Email']?>" /><span id ="emailStatus"></span>
</div>
<br>
<div class='form-group'>
<label>phonenumber*</label>
<input type="number" class="form-control" name="phonenumber" id = "phonenumber" onblur ="phcheck()" placeholder="Enter your phonenumber" value="<?php echo #$_POST['phonenumber']?>" /><span id ="phonenumberStatus"></span>
</div>
<br>
<div>
<?php if (isset($_GET['sponsor']) && $_GET['sponsor'] != "") {?>
<input type="hidden" class="form-control" name="sponsor" id ="sponsor" onblur ="usernamecheck()" placeholder="type in your sponsor username here" value="<?php $sponsor = $_GET['sponsor'];?>" />
<?php }?>
</div>
<br>
<div id="captcha"><img src="captcha.php"></div>
<br>
<div id="refresh"><p> Refresh To Change Code</p></div>
<div id="captcha">
<input type="text" class="form-control" name="recaptcha" id = "recaptcha" onblur ="recaptchacheck()" placeholder="Enter The Code Above" /><span><?php echo #$error_captcha?></span><span id ="recaptchaStatus"></span>
</div>
<div class='form-group'>
<!-- this checkbox needs a name!! Assign name `terms` -->
<input type="checkbox" name="terms" required />
</div>
<div id="terms"> </a><a href="terms.php" >I agree with terms and conditions</a></div>
<div>
<input type='submit' class='btn btn-success' name='submit_signup' value='REGISTER' />
</div>
<br>
</form>
<br>
<div></div>
</div>
<footer>
</footer>
<script lang="javascript" type="text/javascript" src="jqueryfunctions.js"></script>
<script lang="javascript" type="text/javascript" src="ajaxfiles.js">
</script>
</body>
</html>

How to retrieve values from database using php and mysql

I am trying to write a script where I need to retrieve email from the database and send a url link to that email,it works, but I want it to be in proper query, since as a beginner I tried but not sure if the queries are correct, I have trouble retrieving the people_id, when the link is sent i am getting the token but not the student_id, how do I fix this issue
<?php
error_reporting(1);
session_start();
include 'includes/db.php';
include 'includes/tokengen.php';
include('classes/phpmailer/phpmailer.php');
if($_POST["Submit"]=="Submit"){
$idcode=$_POST['idcode'];
$_SESSION['idcode'] = $post['idcode'];
$sql = "SELECT * FROM student WHERE idcode = :idcode";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':idcode', $idcode);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
$email = $result['email'];
//followed a online resource*Doubt
//echo $email;
$token = generateToken();
//echo $token;
$sql = "UPDATE student SET token = :token WHERE email = :email";
//echo $email;
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
$mail = new PHPMailer;
$mail->isSMTP();
//From email address and name
$mail->From = "graymatter.com";
$mail->FromName = "johndoe";
//To address and name
$mail->addAddress("$email", "janedoe");
//echo $email;
//$mail->addAddress("recepient1#example.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("", "Reply");
//CC and BCC
//$mail->addCC("cc#example.com");
//$mail->addBCC("bcc#example.com");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "You Registration Link!";
$mail->Body = "http://www.empty.com/register/registration.php?token=$token&student_id=student_id";
$mail->AltBody = 'Click to Register';
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
}
}
else{
echo 'You are not Registered';
}
}
?>
<div class="container">
<div class="row">
<div class="col-md-5 col-md-offset-3 well">
<form role="form" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="regform">
<fieldset>
<legend>Login</legend>
<div class="form-group">
<div class="col-md-3">
<label for="txt_email" class="control-label">CCODE:</label>
</div>
<div class="col-md-9">
<div class="form-inline">
<div class="form-group">
<input class="form-control" type="text" name="idcode" required placeholder="STUDENT ID" value="<?= isset($_SESSION["idcode"]) ? $_SESSION["idcode"] : ""; ?>"/>
<label for="idcode" generated="true" class="error">
<?= isset($error_hash["idcode"]) ? $error_hash["idcode"] : "" ?>
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" name="Submit" value="Submit" class="btn btn-primary"/>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>

PDO Query not inserting in Database

The following code is created to register a user in my website. When I try to register a user the 'query' is being executed but the new record in the database is not shown.
The following code is the register form:
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="page-header">
<h2>Register Now</h2>
</div>
<div>
<form id="defaultForm" method="post" name="registerform" class="form-horizontal" action="index.php">
<div class="form-group">
<div class="col-lg-11">
<?php include('include/showErrors.php'); ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-5">
<input type="email" class="form-control" name="email" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-5">
<input type="password" class="form-control" name="password" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="age" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Sex</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="sex" autocomplete="off" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="country" autocomplete="off" />
</div>
</div>
<div class="form-group">
<div class="col-lg-8 col-lg-offset-3">
<button name="Submit" type="submit" class="btn btn-primary">Sign up</button>
</div>
</div>
<br>
</form>
</div>
</div>
The following is the doRegister user:
class Registration
{
private $dbCon = null;
public $regSuccessful = false;
public $verificationSuccess = false;
public $errors = array();
public $messages = array();
//the below function will automaticcaly start when a obejct of this class is created
public function __construct()
{
//session_start();
if(isset($_POST["Submit"]))
{
$this->registerUser($_POST['username'], $_POST['password'],$_POST['email'],$_POST['age'],$_POST['sex'],$_POST['country']);
}
else if (isset($_GET["id"]) && isset ($_GET["verification_code"]))
{
$this->verifyUser($_GET["id"], $_GET["verification_code"]);
}
}
//the following methods checks if a database connection is open or not
private function dbConnection()
{
if($this->dbCon != null)
{
return true;
}
else
{
//create database connection
try
{
$this->dbCon = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
return true;
} catch (PDOException $ex) {
$this->errors[] = MESSAGE_DATABASE_ERROR;
return false;
}
}
}
//the following method will handle and the registration errors
private function registerUser($username,$password,$email,$age, $sex,$country)
{
//this will remove extra spaces
$username = trim($username);
$email = trim($email);
$sex = trim($sex);
$country = trim($country);
if(empty($username))
{
$this->errors[] = MESSAGE_USERNAME_EMPTY;
}
else if(empty($password))
{
$this->errors[] = MESSAGE_PASSWORD_EMPTY;
}
else if(empty($country))
{
$this->errors[] = MESSAGE_COUNTRY_EMPTY;
}
else if(empty($sex))
{
$this->errors[] = MESSAGE_SEX_EMPTY;
}
else if(empty($age))
{
$this->errors[] = MESSAGE_AGE_EMPTY;
}
else if(strlen($password) < 6)
{
$this->errors[] = MESSAGE_PASSWORD_TOO_SHORT;
}
elseif (strlen($username) > 64 || strlen($username) < 2)
{
$this->errors[] = MESSAGE_USERNAME_BAD_LENGTH;
}
elseif (!preg_match('/^[a-z\d]{2,64}$/i', $username)) {
$this->errors[] = MESSAGE_USERNAME_INVALID;
} elseif (!preg_match('/^[a-z\d]{2,64}$/i', $country)) {
$this->errors[] = MESSAGE_COUNTRY_INVALID;
}
elseif (!preg_match('/^[a-z\d]{2,64}$/i', $sex)) {
$this->errors[] = MESSAGE_SEX_INVALID;
}
elseif (empty($email)) {
$this->errors[] = MESSAGE_EMAIL_EMPTY;
} elseif (strlen($email) > 64) {
$this->errors[] = MESSAGE_EMAIL_TOO_LONG;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors[] = MESSAGE_EMAIL_INVALID;
}else if ($this->dbConnection())
{
// check if username or email already exists
$check_user_name = $this->dbCon->prepare('SELECT username, email FROM tbl_users WHERE username=:username OR email=:email');
$check_user_name->bindValue(':username', $username, PDO::PARAM_STR);
$check_user_name->bindValue(':email', $email, PDO::PARAM_STR);
$check_user_name->execute();
$result = $check_user_name->fetchAll();
// if username or/and email find in the database
// TODO: this is really awful!
if (count($result) > 0) {
for ($i = 0; $i < count($result); $i++) {
$this->errors[] = ($result[$i]['username'] == $username) ? MESSAGE_USERNAME_EXISTS : MESSAGE_EMAIL_ALREADY_EXISTS;
}
} else {
// check if we have a constant HASH_COST_FACTOR defined (in config/hashing.php),
// if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null
//$hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
//the following will encrypt users password with the PHP 5.5's hash function
//$userPassHash = password_hash($password, PASSWORD_BCRYPT);
// $userPassHash = password_hash( $password, PASSWORD_BCRYPT, array(
// 'cost' => 12
// ));
//this will generate a random hash for email verification
$user_activation_hash = sha1(uniqid(mt_rand()), true);
//the following will write a new user data into the database
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now()), :age, :sex, :country');
$queryUserInsert->bindValue(':username', $username, PDO::PARAM_STR);
$queryUserInsert->bindValue(':userPassHash', $password, PDO::PARAM_STR);
$queryUserInsert->bindValue(':email', $email, PDO::PARAM_STR);
$queryUserInsert->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR);
$queryUserInsert->bindValue(':user_registration_ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$queryUserInsert->bindValue(':age', $age, PDO::PARAM_STR);
$queryUserInsert->bindValue(':sex', $sex, PDO::PARAM_STR);
$queryUserInsert->bindValue(':country', $country, PDO::PARAM_STR);
$queryUserInsert->execute();
//id of the new user registered
//$user_id = $this->dbCon->lastInsertId();
//checks if the query was succesfull, and send verification email
if($queryUserInsert)
{
$this->messages[] = MESSAGE_REGISTRATION_ACTIVATION_SUCCESSFUL;
}
else
{
$this->errors[] = MESSAGE_REGISTRATION_FAILED;
}
}
}
}
}
Screenshot of the Database:
Use this insert query:
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now(), :age, :sex, :country)');
You have added an extra ) after now() function in query; Put it after :country
Change
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now()), :age, :sex, :country');
^ Extra Closing Bracket ^ Closing Bracket For VALUES missing
To
$queryUserInsert = $this->dbCon->prepare('INSERT INTO tbl_users (username, password, email, user_activation_hash, user_registration_ip, user_registration_datetime,age,sex,country) VALUES (:username, :userPassHash, :email, :user_activation_hash, :user_registration_ip, now(), :age, :sex, :country)');
Extra closing bracket in now()
Didn't closed bracket for VALUES.

Categories