php header("Location:) used twice issue - php

I am encountering an issue with this piece of code:
if (!empty($_POST['email']) && !empty($_POST['password'])
&& $_POST['password'] == $_POST['confirm_password']
&& ( !filter_var ($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUE (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
header("Location:succRegister.php");
else : //this part of code is the problem
header("Location:failRegister.php");//
endif;
endif;
?>
I wish I knew why when the statement ($stmt) is not executed in regards to the conditions above, the link (else) doesn't work?
The first link does work.

I think I see what might be the problem. If your first if condition is not met, neither of the headers will be reached. You can move the fail location outside the outer if, so that it will go there by default. Then on the inner if, exit immediately after sending the header.
if (!empty($_POST['email']) && !empty($_POST['password'])
&& $_POST['password'] == $_POST['confirm_password']
&& ( !filter_var ($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUE (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
header("Location: succRegister.php"); // only go here on success
exit();
endif;
endif;
// always go here if you haven't already gone somewhere else
header("Location: failRegister.php");
You can achieve the same thing with
if (!empty($_POST['email']) && !empty($_POST['password'])
&& $_POST['password'] == $_POST['confirm_password']
&& ( !filter_var ($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ) :
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUE (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if ( $stmt->execute() ):
header("Location: succRegister.php"); // only go here on success
else:
header("Location: failRegister.php"); // $stmt->execute failed
endif;
else:
header("Location: failRegister.php"); // $_POST validation failed
endif;
But if you are redirecting to the same page on either reason for failure, this is redundant.

Related

How can I check if a user exists with PDO?

My PDO query is not working for some reason, the page itself doesn't seem to have any error, I've been trying to fix this for like 2 months and nothing worked, I got this "final" code which not seems to have any errors and it's still not working.
<?php
require 'database.php';
$message = '';
if (!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['password'])) {
$sql = "INSERT INTO users (username, email, phone, password) VALUES (:username, :email, :phone, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':phone', $_POST['phone']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);
$query = $con->prepare("SELECT username FROM users WHERE username = :username");
$query->bindParam(':username', $_POST['username']);
$query->execute();
if($query->rowCount() > 0){
?> Este usuario ya existe <?php
}
else {
if($stmt->execute()) {
header('Location: login.php');
}
else {
echo "OcurriĆ³ un error";
}
}
}
?>
I suppose that it's because you have used a inapropriate variable.
in initialisation of $stmt you used $conn and in $query you used $con
make sure to the rigth varaible

Registration PHP Code error

I am facing an error while completing my registration system. My database connection is working properly.
Registration PHP Code:
require 'db.php';
$message = '';
if(!empty($_POST['full_name']) && !empty($_POST['email']) && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['confirm_password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (full_name, email, username, password) VALUES (:email, :password)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':email', $_POST['full_name']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':email', $_POST['username']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
header('Location: index.php');
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
You are binding parameters for values which you have not included in the query,
change,
$sql = "INSERT INTO users (full_name, email, username, password) VALUES (:email, :password)";
to,
$sql = "INSERT INTO users (full_name, email, username, password) VALUES (:full_name, :email, :username, :password)";
and change,
$stmt->bindParam(':email', $_POST['full_name']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':email', $_POST['username']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
to,
$stmt->bindParam(':full_name', $_POST['full_name']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
Now you are actually passing the correct values to the query.
Take note of the following:
Ensure you are validating/sanitizing your user input.
Ensure that you use exit with header to prevent errors.
You are setting the value of $message but not outputting it.

Multiple prepared statements on same page MYSQLI

I have some issues with my code. It seems like I'm not able to have multiple prepared statements which seems a little unusual to me.
I would be glad if you can spot an error or help me because I can't figure out the issue.
My error:
Fatal error: Call to a member function bind_param() on boolean in /Applications/XAMPP/xamppfiles/htdocs/platform/creating_user.php on line 37
I am trying to check if the users email already exists in the database and then register the user.
The code works fine when i dont execute the $check.
$check->execute();
I would also like some response on my workflow (the way my code is built up). is it okay?
Thanks!
<?php
$db = new mysqli("localhost","root","","database");
session_start();
if (isset($_POST)){
if(
!empty($_POST["name"])
& !empty($_POST["city"])
& !empty($_POST["zip"])
& !empty($_POST["email"])
& !empty($_POST["tel"])
& !empty($_POST["password"])
) {
$name = encrypt($_POST["name"]);
$city = encrypt($_POST["city"]);
$zip = encrypt($_POST["zip"]);
$email = encrypt($_POST["email"]);
$tel = encrypt($_POST["tel"]);
$password = encrypt($_POST["password"]);
if(!empty($name) && !empty($city) && !empty($zip) && !empty($email) && !empty($tel) && !empty($password)) {
$check = $db->prepare("SELECT email FROM user WHERE email = ?");
$check->bind_param('s', $email);
$check->execute();
if ($check->num_rows == 1) {
header("Location: index.php");
die();
} else {
$insert = $db->prepare("INSERT INTO user (name, city, zip, email, tel, password, created) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$insert->bind_param("ssssss",$name, $city, $zip, $email, $tel, $password);
if ($insert->execute()){
$db->close();
$_SESSION["user"] = $email;
header("Location: created_user");
die();
} else {
header("Location: create-user");
die();
}
}
} else {
header("Location: create-user");
die();
}
} else {
header("Location: create-user");
die();
}
} else {
header("Location: create-user");
die();
}
?>
On php.net I found this
mysqli::prepare() returns a statement object or FALSE if an error
occurred.
So this mean something is wrong with your $db object. This could be:
Wrong password
Wrong username
...

PHP check if user exists PDO

I'm trying to implement the function where it will check whether if the user already exists in my database be for it will insert all the registration data but it doesn't seem to work =( could someone please help me identify where the error is. really appreciate all the answer in advance.
<?php
require '../ppuyakul/php/db_conn.php';
$message = '';
//Prepare date
$DOB = date("Y-m-d", strtotime( $_POST['year'].'-'. $_POST['month'].'-'. $_POST['day']));
$accessType = "0";
//Check enpty field
if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['fullname']) && !empty($_POST['username']) && !empty($_POST['password_confirmation']) && !empty($_POST['gender']) && !empty($_POST['country']) && !empty($_POST['state']) && !empty($_POST['city']) && !empty($_POST['day']) && !empty($_POST['month']) && !empty($_POST['year'])):
// Enter the new user in the database
$sql = "INSERT INTO assignment2 (fullname, username, email, password, gender, country, state, city, DOB, type) VALUES (:fullname, :username, :email, :password, :gender, :country, :state, :city, :DOB, :type)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':fullname', $_POST['fullname']);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':gender', $_POST['gender']);
$stmt->bindParam(':country', $_POST['country']);
$stmt->bindParam(':state', $_POST['state']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':DOB', $DOB);
$stmt->bindParam(':type', $accessType);
$chk = $conn->prepare("SELECT username FROM assignment2 WHERE username = :name");
$chk->bindParam(':name', $username);
$chk->execute();
if($chk->rowCount() > 0):
$message = 'Error ! ! User already exists';
else:
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
endif;
?>
According to #Paul T. I finally found the solution here is the final code, thanks so much again for your help #Paul T.
$username = $_POST['username'];
$chk = $conn->prepare("SELECT username FROM assignment2 WHERE username = :name");
$chk->bindParam(':name', $username);
$chk->execute();
if($chk->rowCount() > 0):
$message = 'Error ! ! User already exists';
else:
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
endif;

Check if the email exists using pdo

This is the section I use to add users.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: ./index.php");
}
require 'conn.php';
$message = '';
if(!empty($_POST['name']) &&!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
I personally do it by using a query and an if statement
$query = $conn->prepare("SELECT * FROM users WHERE email = :email");
$query->bindParam(':email', $_POST['email']);
if ($query->rowcount() = 0)
{
// insert account into database
}
else {
// display error message
}
To check if the email exists or not, you have to write a query whether that email is stored in the database. If the query result is not empty, you can show a message that the email exists. If the query result is empty, you can make him a new user.
For that you have to write this query
$sql="select name from user where email='$email'";
$stmt = $conn->prepare($sql);
if ($stmt->rowcount() = 0)
{
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
}
else {
$msg="Email already exists";
}

Categories