Check row exists with PDO [duplicate] - php

This question already has answers here:
Row count with PDO
(21 answers)
Closed 4 years ago.
I cannot figure this out, I've been reading numerous Stack overflow threads and I keep getting an issue,
right now if the user types anything, regardless if it is the same username or email, it would come up with an error. Please help!
I want the error message to appear when the user types an username or email that is already on the database.
$sql = "SELECT count(*) FROM users WHERE user_email = :email OR user_name = :username";
$query1 = $DBH->prepare($sql);
$query1->execute(array(':username' => $username,':email' => $email));
if ($query1->rowCount() > 0){
// User Exists
$error = "Username or E-Mail in Use";
} else{
// User Does Not Exist
//No errors - let’s create the account
//Encrypt the password with a salt
$encryptedPass = password_hash($_POST['password'], PASSWORD_DEFAULT);
//Insert DB
$query = "INSERT INTO users (user_email, user_password, user_forename, user_lastname, user_name, user_gender, user_country, user_number) VALUES (:email, :password, :firstname, :lastname, :username, :gender, :country, :mobile)";
$result = $DBH->prepare($query);
$result->bindParam(':username', $_POST['username']);
$result->bindParam(':firstname', $_POST['firstname']);
$result->bindParam(':lastname', $_POST['lastname']);
$result->bindParam(':email', $_POST['email']);
$result->bindParam(':gender', $_POST['gender']);
$result->bindParam(':country', $_POST['country']);
$result->bindParam(':mobile', $_POST['mobile']);
$result->bindParam(':password', $encryptedPass);
if($result->execute()){
echo '<div class="alert alert-success" role="alert">Registration Successful!</div>';
echo "<script> window.location.assign('index.php?p=login'); </script>";
}
}
EDIT
$stmt = $DBH->prepare("SELECT COUNT(*) FROM users WHERE user_email = :email OR user_name = :username");
$stmt->execute(array(':username' => $username,':email' => $email));
$count = $stmt->fetchColumn();
var_dump($count);
if ($count > 0) {
$error1 = "Username or E-Mail in Use. Please try another.";
}
if(!$error){
//No errors - let’s create the account
//Encrypt the password with a salt
$encryptedPass = password_hash($_POST['password'], PASSWORD_DEFAULT);
//Insert DB
$query = "INSERT INTO users (user_email, user_password, user_forename, user_lastname, user_name, user_gender, user_country, user_number) VALUES (:email, :password, :firstname, :lastname, :username, :gender, :country, :mobile)";
$result = $DBH->prepare($query);
$result->bindParam(':username', $_POST['username']);
$result->bindParam(':firstname', $_POST['firstname']);
$result->bindParam(':lastname', $_POST['lastname']);
$result->bindParam(':email', $_POST['email']);
$result->bindParam(':gender', $_POST['gender']);
$result->bindParam(':country', $_POST['country']);
$result->bindParam(':mobile', $_POST['mobile']);
$result->bindParam(':password', $encryptedPass);
if($result->execute()){
echo '<div class="alert alert-success" role="alert">Registration Successful!</div>';
// echo "<script> window.location.assign('index.php?p=login'); </script>";
}
}
var dump = string(1) "0"

A few ways to go about this. As #chris85 mentioned you need to actually fetch the result instead of using rowCount().
Edit: Removed the first example.
<?php
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE user_email = :email OR user_name = :username");
$stmt->execute(array(':username' => $username,':email' => $email));
$count = $stmt->fetchColumn();
if ($count > 0) {
$error = "Username or E-Mail in Use";
} else {
...

Related

Trying to create update profile page in PHP PDO

I am trying to create an update profile page in PHP. But, I keep running into an error. When I submit the form to update the profile, there are four fields. Username, email, firstname, and lastname. Say I want to change only the first name of the user, when I submit the form, it gives me an error telling me the username/email/lastname is taken because that was already auto-filled in.
Here is my update profile form, the fields contain user information pulled from the database
Here is my update profile code that goes along with the form
// Queries
if (isset($_POST['userprofileupdate'])) {
$firstname = mysqli_real_escape_string($conn, $_POST['name_1']);
$lastname = mysqli_real_escape_string($conn, $_POST['name_2']);
$email = mysqli_real_escape_string($conn, $_POST['email_1']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
// Check if Email exists
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE `email` = :email ');
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
$Count = $stmt->rowCount();
// Check if username exists
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE `username` = :username ');
$stmt->bindParam(":username", $username, PDO::PARAM_STR);
$stmt->execute();
$Count1 = $stmt->rowCount();
if ($Count < 1) {
if ($Count1 < 1) {
$query = "UPDATE users SET username=?, firstname=?, lastname=?, email=? WHERE id=?";
$stmt = $pdo->prepare($query);
$stmt->bindParam('ssssi', $username, $firstname, $lastname, $email, $id);
$stmt->execute();
unset($_SESSION['username']);
unset($_SESSION['firstname']);
unset($_SESSION['lastname']);
unset($_SESSION['role']);
unset($_SESSION['email']);
unset($_SESSION['password']);
session_destroy();
header('Location: /panel/login?profile_changed');
} else {
header('Location: /panel/profile?username_taken');
}
} else {
header('Location: /panel/profile?email_taken');
}
}
$stmt = $pdo->prepare("SELECT * FROM users WHERE `email`=':email'");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
/// update
$sql = "UPDATE users SET username=?, firstname=?, lastname=?, email=?
WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$firstname, $lastname, $email, $id]);
or please read fully this article for complete understand
https://phpdelusions.net/pdo_examples/select

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

Seeing whether the email used is in the database - PHP

I'm attempting to access my database to see if the email has been
used previously. All my attempts have failed. I can get the form to
enter the information into the database but that is it. I'm very new
to PHP so any help is appreciated.
<?php
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$sql = "INSERT INTO noodles_gamification (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ){;
$message = 'Successfully created new user';
}else {
$stmt = $conn->prepare('SELECT email FROM noodles_gamification WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'email provided is already in use.';
}
}
endif;
?>
I think you need to check if email is already exist or not before inserting new record to database Just modify your if condition some think like
<?php
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$stmt = $conn->prepare('SELECT email FROM noodles_gamification WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'email provided is already in use.';
} else {
$sql = "INSERT INTO noodles_gamification (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ){;
$message = 'Successfully created new user';
}
}
else {
}
endif;
?>

Verify e-mail is not already registered PHP Mysql

Right now I am trying to set up a user registration page, and I've been having trouble with verifying that the e-mail is not already in use. I figured all I had to do was make a query to my database to check and see if the e-mail was already in use. This seems pretty straight forward, so I don't know why it's giving me such a problem.
I've read several posts, and tried several approaches with PDO and mysqli, but I have still yet to get this script to function properly. Any help would be greatly appreciated.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])&& !empty($_POST['firstname'])&& !empty($_POST['lastname'])&& !empty($_POST['phone'])&& !empty($_POST['address'])&& !empty($_POST['city'])&& !empty($_POST['zip'])):
//check to see if e-mail is already being used
//This method always says that the email is already in use, even if I am entering a new one.
/*
$records = $conn->prepare('SELECT * FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if( count($results) > 0){
$message = "Sorry, that E-mail address is already registered to an account.";
}
*/
//this one never says that the email is in use.
/*
$email = $_POST['email'];
$query = mysqli_query($conn, "SELECT * FROM users WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
$message = "Sorry, that E-mail address is already registered to an account.";
}
*/
//this was the last method I tried, and it also never says that the email is in use.
try{
$stmt2 = $conn->prepare('SELECT `email` FROM `user` WHERE email = ?');
$stmt2->bindParam(1, $_POST['email']);
$stmt2->execute();
while($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
if($stmt2->rowCount() > 0){
//echo "The record exists!";
$message = "Sorry, that E-mail address is already registered to an account.";
}
else{
// Enter the new user in the database
$sql = "INSERT INTO users (email, password, firstname, lastname, phone, address, city, zip) VALUES (:email, :password, :firstname, :lastname, :phone, :address, :city, :zip)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':firstname', $_POST['firstname']);
$stmt->bindParam(':lastname', $_POST['lastname']);
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':address', $_POST['address']);
$stmt->bindParam(':city', $_POST['city']);
$stmt->bindParam(':zip', $_POST['zip']);
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
}
endif;
?>
When doing COUNT(*) the server(MySQL) will only allocate memory to store the result of the count and its faster too.
this part of your code that must be corrected:
$records = $conn->prepare('SELECT count(*) FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_NUM);
echo $results[0];

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