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.
Related
This question already has an answer here:
PHP PDO prepared statements
(1 answer)
Closed 1 year ago.
I am using PHP and PDO, the problem is when I click on the submit button the data is not inserted into the Database. There are no errors at all, I am not sure what's causing it. I've tried a lot of things and still can't manage to find a solution.
This is my code:
<?php
function cl($info){
return preg_replace("|[^\w]|", "", $info);
}
function cl2($info){
return preg_replace("|[^\w]|", "", $info);
}
function check_email($email){
$exit = FALSE;
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
return $exit = TRUE;
}
else {
return $exit;
}
}
if (isset($_POST['register'])) {
$errors = [];
$username = cl($_POST['username'] ?? '');
$password = cl2($_POST['password'] ?? '');
$email = $_POST['email'] ?? '';
try {
$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
$check_username = $conn->prepare("SELECT * FROM accounts WHERE name = :username");
$check_username->bindParam(':username', $username, PDO::PARAM_STR);
$check_username->execute();
if($check_username->rowCount()) {
array_push($errors, 'Username already in use, please select a new one.');
} else if(empty($username) || strlen($username) < 4 || strlen($username) > 13) {
array_push($errors, 'Invalid username, please select another one.');
} else if(empty($password) || strlen($password) < 4 || strlen($password) > 20) {
array_push($errors, 'Invalid password, please select another one.');
} else if(empty($email) || !check_email($_POST['email'])) {
array_push($errors, 'Invalid password, please select another one.');
}
if(empty($errors)) {
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES ($username,$password,$email)");
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->execute();
echo '<br />';
echo ' <div class="alert alert-success text-center" role="alert">
Account created succesfully.
</div>';
} else {
foreach($errors as $error) {
echo '<br />';
echo '<div class="alert alert-danger text-center" role="alert">';
echo $error;
echo '</div>';
}
}
}
?>
And the form:
<form method="POST">
<div class="form-group">
<label for="InputUsername">Username</label>
<input type="text" class="form-control" id="InputUsername" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="password">
</div>
<div class="form-group">
<label for="inputEmail">Email address</label>
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" name="email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="rules">
<label class="form-check-label" for="rules">I have read the rules before creating a new account.</label>
</div>
<br />
<button type="submit" class="btn btn-primary" name="register">Submit</button>
</form>
I am trying this using Wamp, in a local development. If anyone could help me I would really appreciate it.
Okay now after adding this to my code:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I am getting the following error:
Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.accounts' doesn't exist
But the table exists in my db. This is acting weird.
From what I can see this line is wrong
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES ($username,$password,$email)");
It should be
$query = $conn->prepare("INSERT INTO accounts (name,password,email) VALUES (:username,:password,:email)");
I THINK it would've worked had you put quotes around the variables but you look like you want to prevent sql injection properly.
I'm currently trying to create a registration form for my website (this has worked in the past)
and I keep getting a registration fail, no errors are appearing - has anyone got any ideas why?
I used to have a recaptcha function within it but I don't see that being the issue.
I've tried to fix this for days.
PHP:
if (isset($_POST['register'])) {
if (!empty($username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING)) AND !empty($email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL)) AND !empty($password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING)) AND !empty($password2 = filter_input(INPUT_POST, 'password2', FILTER_SANITIZE_STRING))) {
$password = EncryptPasswords($password);
$password2 = EncryptPasswords($password2);
$qry = $con->prepare("SELECT * FROM `users` WHERE `username`=:username");
$qry->execute(["username"=>$username]);
if ($qry->rowCount() == 0) {
$qry = $con->prepare("SELECT * FROM `users` WHERE `email`=:email");
$qry->execute(["email"=>$email]);
if ($qry->rowCount() == 0) {
if ($password == $password2) {
$random = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 86)), 0, 86);
$RANDOMqry = $con->prepare("SELECT * FROM `users` WHERE `access_token`=:id");
$RANDOMqry->execute(["id"=>$random]);
while ($RANDOMqry->rowCount() > 0) {
$random = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 86)), 0, 86);
$RANDOMqry = $con->prepare("SELECT * FROM `users` WHERE `access_token`=:id");
$RANDOMqry->execute(["id"=>$random]);
}
$REGqry = $con->prepare("INSERT INTO `users` (`username`, `email`, `email_ver`, `password`, `access_token`, `registered`, `rank`)
VALUES
(:user, :email, :veri, :password, :access, :times, :ranks)");
$REGexct = $REGqry->execute(["user"=>$username, "email"=>$email, "veri"=>"no", "password"=>$password, "access"=>$random, "times"=>$timestamp, "ranks"=>"2"]);
if ($REGexct) {
$qry = $con->prepare("SELECT * FROM `users` WHERE `username`=:username");
$qry->execute(["username"=>$username]);
$row = $qry->fetch();
setcookie('accesstoken',$row->access_token,time()+(86400 * 14),'/');
setcookie('_uc_id',$row->id,time()+(86400 * 14),'/');
setcookie('_uc_pw',$row->password,time()+(86400 * 14),'/');
$_SESSION['cerror'] = '<div class="alert alert-success">Your account has been registered, please enter the following information correctly or leave it for a further date.</div>';
header('Location: /members/register-details');
exit();
} else {
$_SESSION['cerror'] = '<div class="alert alert-danger"><strong>Error: </strong>Registration Failed.</div>';
header('Location: '.$cwd);
exit();
}
} else {
$_SESSION['cerror'] = '<div class="alert alert-danger"><strong>Error: </strong>Passwords do not match.</div>';
header('Location: '.$cwd);
exit();
}
} else {
$_SESSION['cerror'] = '<div class="alert alert-danger"><strong>Error: </strong>That email is already in use, you\'ll need to pick another.</div>';
header('Location: '.$cwd);
exit();
}
} else {
$_SESSION['cerror'] = '<div class="alert alert-danger"><strong>Error: </strong>That username already exists, you\'ll need to pick another.</div>';
header('Location: '.$cwd);
exit();
}
} else {
$_SESSION['cerror'] = '<div class="alert alert-danger"><strong>Error: </strong>You must fill in all of the details to log in.</div>';
header('Location: '.$cwd);
exit();
}
}
HTML:
<form action method="post">
<div class="form-group">
<input name="username" type="text" class="form-control input-lg" placeholder="Choose a username" autocomplete="off" autofocus />
</div>
<div class="form-group">
<input name="email" type="email" class="form-control input-lg" placeholder="Enter your email address" autocomplete="off" />
</div>
<div class="form-group">
<input name="password" type="password" class="form-control input-lg" placeholder="Choose a password" autocomplete="off" />
</div>
<div class="form-group">
<input name="password2" type="password" class="form-control input-lg" placeholder="Confirm your password" autocomplete="off" />
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdJYZAUAAAAALere0Qs9ns7S4nMUajPKsHWXGOr"></div>
</div>
<div class="form-group">
<button name="register" type="submit" class="button button-login pull-right"><i class="fas fa-plus-square"></i> Register</button>
</div>
</form>
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>
Here is my code,
HTML:
<div class="form-content">
<form method="post" action="../controller/regprocess.php">
<div class="form-group">
<label>Username</label>
<input type="text" id="Rusername" name="Rusername" required="required" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="Rpassword" name="Rpassword" required="required" />
</div>
<div class="form-group">
<label>First Name</label>
<input type="text" id="RfirstName" name="RfirstName" required="required" />
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" id="RlastName" name="RlastName" />
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="Remail" name="Remail" required="required" />
</div>
<div class="form-group">
<label>Phone</label>
<input type='number' id="Rphone" name="Rphone" required="required" />
</div>
<div class="form-group">
<button type="submit">Register</button>
</div>
</form>
</div>
regprocess PHP:
<?PHP
session_start();
//connect to the database
require('../model/database.php');
//Load user functions
require('../model/functions_users.php');
//retrieve the registration details into the form
$username = $_POST['Rusername'];
$password = $_POST['Rpassword'];
$firstName = $_POST['RfirstName'];
$lastName = $_POST['RlastName'];
$email = $_POST['Remail'];
$phone = $_POST['Rphone'];
//call the add_user() function
$result = add_user($username, $password, $firstName, $lastName, $email, $phone);
//create user messages
if($result)
{
//create a success message to display on page
$_SESSION['success'] = 'Thank you for creating an account. Please login.';
//redirect to products.php
header('location: ../view/login-registration.php?page=login');
}
else
{
//create a error message to display on page
$_SESSION['error'] = 'An error has occurred. Please try again.';
//redirect to product_add_form.php
header('location: ../view/login-registration.php?page=login');
}?>
and finally my result function:
function add_user($username, $password, $firstName, $lastName, $email, $phone)
{
global $conn;
$sql = "INSERT INTO users (username, password, firstName, lastName, email, phone) VALUES (:username, :password, :firstName, :lastName, :email, :phone)";
$statement = $conn->prepare($sql);
$statement->bindValue(':username', $username);
$statement->bindValue(':password', $password);
$statement->bindValue(':firstName', $firstName);
$statement->bindValue(':lastName', $lastName);
$statement->bindValue(':email', $email);
$statement->bindValue(':phone', $phone);
$result = $statement->execute();
$statement->closeCursor();
return $result;
}
I have two parent divs overlapping each other, one is hidden (registration form) until a panel is clicked and sets div active to appear on top of the login form. The active div (login form) submit button works but the 2nd form (registration form) submit button does not work.
JS:
$(document).ready(function() {
var panelOne = $('.form-panel.two').height(),
panelTwo = $('.form-panel.two')[0].scrollHeight;
$('.form-panel.two').not('.form-panel.two.active').on('click', function(e) {
e.preventDefault();
$('.form-toggle').addClass('visible');
$('.form-panel.one').addClass('hidden');
$('.form-panel.two').addClass('active');
$('.form').animate({'height': panelTwo
}, 200);
});
$('.form-toggle').on('click', function(e) {
e.preventDefault();
$(this).removeClass('visible');
$('.form-panel.one').removeClass('hidden');
$('.form-panel.two').removeClass('active');
$('.form').animate({
'height': panelOne
}, 200);
});
});
$('.form-panel.two').not('.form-panel.two.active').on('click', function(e) {
/*e.preventDefault(); --> it looks like this is what is preventing your form submission but it is hard to tell without the full file and error log */
$('.form-toggle').addClass('visible');
$('.form-panel.one').addClass('hidden');
$('.form-panel.two').addClass('active');
$('.form').animate({'height': panelTwo
}, 200);
});
I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.