Checking only email, not username - php

I have this code which checks email availability from database, but it's only checking email and not username. I want to check both email and username, I tried to check them through the code below but it doesnt work.
What is wrong with the code?
<?php
require_once './config.php';
if (isset($_POST["sub"])) {
$fname = ($_POST["fname"]);
$lname = ($_POST["lname"]);
$name = ($_POST["username"]);
$pass = ($_POST["password"]);
$email = ($_POST["email"]);
$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id ";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":email_id", $email);
$stmt->bindValue(":username_id", $name);
$stmt->execute();
$result = $stmt->fetchAll();
if ($result[0]["count"] > 0) {
echo "<div style='color:red;' class='errorbox'>Incorrect Username or Password</div><br>";
} else {
$sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
}
}
}
?>

You have a problem with your SQL statement, you are checking that both email and username are together try changing your statement from
$sql = "SELECT COUNT(*) AS count from users where email = :email_id and username = :username_id "
to
$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id "
This should force a return of 1 whenever either the username or email appears proving that they are not unique

You are using and condition. If you use or condition means it will be fine.
$sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";

Typographical error. This line should be replaced:
$stmt->bindValue(":username_id", $email);
should be replaced with:
$stmt->bindValue(":username_id", $name);

Maybe you have an error here:
$stmt->bindValue(":email_id", $email); //ok
$stmt->bindValue(":username_id", $email); //you bind with $email again .. is it normal ?
You should validate your $_POST datas with !empty i.e.:
if(!empty($_POST["email"]) $email = $_POST["email"]) ... because with your actual code you could make sql queries with empty $email = null

Related

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

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

Select then Insert PHP query

Ho can I check the database first if a user exists then use a insert statement if it does not. The code currently only executes the select statement.
<?php
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_query($dbconn, $query_check_user)) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
<?
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
//Query for count
$query_check_user = "SELECT count(*) as total FROM Users WHERE username = '$user'";
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
//Execute query for count
$result = mysqli_query($dbconn, $query_check_user);
//Fetch result
$data = mysqli_fetch_assoc($result);
//Check if count >0
if ($data['total']>0) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
?>
you can use mysqli_num_rows(); to check the number if result if it is greater then 0 then user exist else insert user data.
my example :
include_once('includes/dbconn.php');
if (isset($_POST['submitted'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$query_result = mysqli_query($query_check_user);
$query = "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')";
if (mysqli_num_rows($query_result) > 0) {
echo "user already exists";
mysqli_close($dbconn);
}else{
mysqli_query($dbconn, $query);
}
}
as I get from your question is, you want to insert the user if the user doesn't exist, right?
$query_check_user = "SELECT username FROM Users WHERE username = '$user'";
$b = mysqli_query($dbconn,$query_check_user);
$a = mysqli_num_rows($b);
if($a<0):
mysqli_query(dbconn, "INSERT INTO Users(firstname, lastname, username, password) VALUES ('$fname','$lname','$user','$pass')");
endif;

ERROR WHILE INSERTING USING MYSQLI

i'm new to this PHP please help me here i'm unable to insert values into table.
But if i gave values directly to insert command in place of variables it works.
<?php
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users2 WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
?>
$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("sss", $name, $email, $password);
if (!$stmt->execute()) {
die($stmt->error);
}
I don't know what is the problem in my above question but
i used the above query instead of the one i used the in question and Boom it is a success.
if any one of you know whats the problem in the question please let me know.
You have to concat the variable in string of insert not just put as variable
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")
or
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")
You should use prepare statement for this mysql_real_escape_string-versus-Prepared-Statements
Never use md5() is-md5-considered-insecure
Prefer password_hash() or password_verify() Manuel
``

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";
}

SELECT * FROM multiple column

I am absolute beginner in creating database and
I only know that we can use,
"SELECT * FROM users WHERE username = '$username' and password = '$password'";
but, what if there is multiple table in my SQL and I want to select them all?
can I just do,
"Select * from users where username = '$username' and password = '$password' and email = '$email' and address = '$address' and phone = '$phone'";
Here are my PHP script:
public function does_user_exist($username,$password,$email,$address,$phone){
$query = "Select * from users where username = '$username' and password = '$password' and email = '$email' and address = '$address' and phone = '$phone'";
$result = mysqli_query($this->connection, $query);
if(mysqli_num_rows($result) > 0){
$json['success'] = 'Welcome '.$email;
echo json_encode($json);
mysqli_close($this->connection);
} else {
$query = "Insert into users(username, password, email, address, phone) values ('$username','$password','$email', '$address', '$phone')";
$is_inserted = mysqli_query($this->connection, $query);
if ($is_inserted == 1){
$json['success'] = 'Account created, welcome '.$email;
} else {
$json['error'] = 'Wrong password ';
}
echo json_encode($json);
mysqli_close($this->connetion);
}
}
UPDATE
<?php
require_once 'connection.php';
header('Content-Type: application/json');
class User {
private $db;
private $connection;
function __construct() {
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
}
public function does_user_exist($username,$password,$email,$address,$phone){
$query = ("Select * from users where username = '$username' and password = '$password' and email = '$email' and address = '$address' and phone = '$phone'");
$result = mysqli_query($this->connection, $query);
if(mysqli_num_rows($result) > 0){
$json['success'] = 'Welcome '.$email;
echo json_encode($json);
mysqli_close($this->connection);
} else {
$query = "Insert into users(username, password, email, address, phone) values ('$username','$password','$email', '$address', '$phone')";
$is_inserted = mysqli_query($this->connection, $query);
if ($is_inserted == 1){
$json['success'] = 'Account created, welcome '.$email;
} else {
$json['error'] = 'Wrong password ';
}
echo json_encode($json);
mysqli_close($this->connetion);
}
}
}
$user = new User();
if (isset($_POST['username'], $_POST['password'], $_POST['email'], $_POST['address'], $_POSt['phone'])){
$username = $POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$address = $_POST['address'];
$phone = $_POST['phone'];
if(!empty($username) && !empty($password) && !empty($email) && !empty($address) && !empty($phone)){
$encrypted_password = md5($password);
$user -> does_user_exist($username,$encrypted_password,$email,$address,$phone);
} else {
echo json_encode("You must fill all fields!")
}
}
?>
Hopefully you guys can help, I really appreciate the answers.
You have to use JOIN Queries. Try the below SQL Statement
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Refer this JOIN SQL SO Answers
What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
Difference in MySQL JOIN vs LEFT JOIN
Mysql join query
Generally speaking you will want to use JOIN to do this, and you will need to have values in common between your tables, which act as foreign keys, referencing corresponding values in other tables.
EDIT
Updates to the question and comments indicate that the original question was slightly misphrased. Yes, you can absolutely reference/use/compare/evaluate numerous columns in a single query. The example you posted is a good example:
SELECT (column1, column2) FROM users WHERE username = $username AND email = $email
And so on, for as many columns as the table has. You can also use the OR operator, which has the effect of including any row that matches on username OR on email (or whatever other columns you like).

Categories