how to rowCount for two values in one query using pdo? - php

I am trying to create a signup page and need to validate if username and email already exit.
If I do it in two queries, it works fine, but switch to one query, then it doesn't work properly, it doesn't validate one of value sometimes.
I tried as following but its not working properly, sometimes it doesn't validate for email or username:
$uname = $_POST['username'];
$email = $_POST['email'];
$sql = "SELECT uid FROM users WHERE username = :username OR email = :email";
$stmt1 = $pdo->prepare($sql);
$stmt1->bindParam(":username", $uname, PDO::PARAM_STR);
$stmt1->bindParam(":email", $email, PDO::PARAM_STR);
$stmt1->execute();
if($stmt1->rowCount() == 1){
$rows = $stmt1->fetch();
if($rows['username'] == 1){
$errors['username'] = "Username already in use.";
}else{
$username = $uname;
}
if($rows['email'] == 1){
$errors['email'] = "Email already in use.";
}else{
$email= $email;
}
}
unset($stmt1);

rowCount method returns >= 1 records when username or email match. Try that code:
$username = $_POST['username'];
$email = $_POST['email'];
$errors = array();
$sql = "SELECT username, email FROM users WHERE username = :username OR email = :email";
$stmt1 = $pdo->prepare($sql);
$stmt1->bindParam(":username", $username, PDO::PARAM_STR);
$stmt1->bindParam(":email", $email, PDO::PARAM_STR);
$stmt1->execute();
if($stmt1->rowCount() > 0){
$rows = $stmt1->fetchAll();
foreach($rows as $row) {
if($row['username'] === $username) {
$errors['username'] = "Username already in use.";
}
if($row['email'] === $email) {
$errors['email'] = "Email already in use.";
}
}
$stmt1->closeCursor();
}

You Just get count from this query
$sql = "SELECT uid FROM users WHERE username = :username OR email = :email";
instead of
$sql = "SELECT uid,count(uid) FROM users WHERE username = :username OR email = :email";
Hope it will help with single query

Related

PHP Always return "Incorrect Email or Password" user

PHP always return "Incorrect Email or Password"..
even though the Email and Passwd are correct at the login area,
could someone help me?
$sql = "SELECT id, name FROM users WHERE email = :email AND password = :password";
$stmt = $PDO->prepare($sql);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $passwordHash);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($users) <= 0)
{
echo "Incorrect Email or Password";
exit;
}
// pega o primeiro usuário
$user = $users[0];
session_start();
$_SESSION['logged_in'] = true;
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
header('Location: index.php');
?>

PHP functions seems to have an issue

something in this code doesnt work correctly. So need your help.
I have written a function in an external file:
function userExists($conn, $user){
$sql = "SELECT COUNT(*) FROM user WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $user);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0):
return true;
else:
return false;
endif;
}
And i call this function here:
if(!empty($_POST['email']) && !empty($_POST['password'])):
$email = $_POST['email'];
$password = $_POST['password'];
$records = $conn->prepare('SELECT id,username,email,password,active FROM user WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(userExists($conn, $email) === false){
echo 'False';
}else{
echo 'True';
}
endif;
But the output is everytime true.. maybe I can't see the wood for the trees.
Thx
Results will be greater than 0 at all times because your query is returning the value 0. So results does contain a value. Rather do this
"SELECT COUNT(*) AS Total FROM user WHERE email = :email";"
if($result['Total'] > 0)
{.....}

check if user exists statement works while email statement doesn't in pdo

There's this really weird problem I just encountered. User check statement works while email statement doesn't for some reason. Here is the code also $con is defined outside the two ifs. I don't think that's the problem because user name check does work.
if(!empty($username)){
$username = $_POST['username'];
$stmt = $con->prepare("SELECT username from users where username= :name");
$stmt->bindParam(':name', $username);
$stmt->execute();
$rowcount = $stmt->rowCount($stmt);
if($rowcount > 0){
$errors[] = "name taken";
}
/* doesn't work for some reason */
if(!empty($email)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
filter_var($email,FILTER_SANITIZE_EMAIL);
$stmt = $con->prepare("SELECT email from users where email= :email");
$stmt->bindParam(':email', $email);
$stmt->execute();
$rowcount = $stmt->rowCount($stmt);
if($rowcount > 0){
$errors[] = "email is already taken";
}
}
}
}
As you can see the username errors[] does work while the email doesn't. I even tried echoing it out still no hope :(
You should assign $email before using it in if statement. Therefore, initialize it after $username, for example:
if(!empty($username)){
$username = $_POST['username'];
$email = $_POST['email'];
...

INSERT INTO SQL php Function does not work

I have managed to write a php script that checks if a username already exists in the database and only adds a new user if it does not already exist.
This is my php script:
<?php
require "init.php";
if(isset($_POST['username']) && isset($_POST['forename']) && isset($_POST['surname']) && isset($_POST['password'])){
$username = $_POST['username'];
$forename = $_POST['forename'];
$username = $_POST['surname'];
$password = $_POST['password'];
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon -> prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($username);
if($result->fetch()){
echo "Can't add new user as it already exists!";
}
else{
$stmt_two = "INSERT INTO users (username, forename, surname, password)
VALUES(?, ?, ?, ?)";
$result_two = $dbcon -> prepare($stmt_two);
$result_two->bind_param('ssss', $username, $forename, $surname, $password);
$result_two->execute();
$result_two->close();
echo json_encode("Success");
}
}
?>
I believe the records are not being inserted or being inserted intermittently due to the fact that I have more than one prepared statement. If I just do the INSERT INTO statement on its' own with the SELECT FROM statement - the records are added almost instantly.
Why is this and what is wrong with my code?
Thanks
Just as I have said in the comments, don't over complicate and just check the number of rows found. No need to fetch anything. You're just checking if that user exists anyway.
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->store_result();
if($result->num_rows() > 0) { // if it exists
} else {
// make your insertions
}
And another note:
isset can take multiple arguments:
if(isset($_POST['username'], $_POST['forename'], $_POST['surname'], $_POST['password'])) {
// and so on
}
Edit: Another flavor (using COUNT() of MySQL):
$stmt = "SELECT COUNT(username) FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($count);
$result->fetch();
if($count > 0) { // exists
} else {
// do something else
}

After selecting all from a certain row, is there a way to grab data from certain columns not defined?

So my SELECT statement is selecting all from a row in the users table. There is a column in that row labeled "user_level" and I want to use the data from that column to differentiate between an admin and a guest. Is there a way to use "user_level" (and maybe bind it to a session variable) without me having to write another SELECT statement?
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = :name and
user_password = :password");
$query->bindValue(":name", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
//user entered correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//user entered false details
$error = 'Incorrect details!';
}
}
}
You don't need no rowCount here.
as well as half of the duplicated and triplicated code.
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT user_level FROM users WHERE user_name = ? and user_password = ?";
$stm = $pdo->prepare($sql);
$srm->execute(array($username,$password));
$level = $stm->fetchColumn();
if ($level !== FALSE) {
//user entered correct details
$_SESSION['user_level'] = $level;
header('Location: index.php');
exit();
}
}
$error = 'Incorrect details!';

Categories