mysqli_query gives empty value - php

Im creating a login system for my website.
I got the problem that my mysqli_query is empty:
The code: $r = mysqli_query($dbc, $q); returns empty.
I think the problem is in the sql language that i pass it:
$q = "SELECT userid, fname, lname FROM User WHERE email='$e' AND pass=SHA1('$p')";
If i execute the sql above with the data that im actually is fetching from the form then i will get the result Im looking for. So i think its the php and sql combined that got an error.
if(empty($errors)){
$q = "SELECT userid, fname, lname FROM User WHERE email='$e' AND pass=SHA1('$p')";
$r = mysqli_query($dbc, $q);
//Check for right data
$errors[] = $e;
$errors[] = $p;
//Check if connection is up
if($dbc != null){
$errors[] = "Connection up";
}
//Check query
if(is_null($r)){
$errors[] = "Query is null";
}
//Check query for being empty
if(empty($r)){
$errors[] = "Its empty";
}
if( mysqli_num_rows($r) == 1){
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array(true, $row);
}else{
$errors[] = "Email address and password not found.";
}
return array(false, $errors);
}

You can try this
if(empty($errors)){
$p = sha1($p);
$q = "SELECT userid, fname, lname FROM User WHERE email = '$e' AND pass = '$p'";
$r = mysqli_query($dbc, $q);
if(!$r){
die(mysqli_error($dbc));
}
//Check for right data
$errors[] = $e;
$errors[] = $p;
//Check if connection is up
if($dbc != null){
$errors[] = "Connection up";
}
//Check query
if(is_null($r)){
$errors[] = "Query is null";
}
//Check query for being empty
if(empty($r)){
$errors[] = "Its empty";
}
if( mysqli_num_rows($r) > 0){
$row = mysqli_fetch_assoc($r);
return array(true, $row['userid'], $row['fname'], $row['lname']);
}else{
$errors[] = "Email address and password not found.";
}
return array_merge(array(true), $errors);
}

Related

ELSE statement doesn't return if while loop returns empty

I'm working on a script that checks to see if an email exists in the database barn_users, in order to reset a password. And if the email doesn't exists, the token/code is not generated and stored in the database. Everything works perfectly, until I enter an email that is not in the system. The else statement with the error "Could not find email in the system.", doesn't trigger. What am I doing wrong to not get that?
$sql_1 = "SELECT * FROM password_reset WHERE email='$email'";
$sql_2 = "SELECT * FROM barn_users WHERE email='$email'";
$generate = mysqli_query($conn, $sql_1);
$searchEmail = mysqli_query($conn, $sql_2);
while($row = mysqli_fetch_array($searchEmail)) {
if(mysqli_num_rows($searchEmail) > 0) {
if (mysqli_num_rows($generate) > 1) {
} else if (mysqli_num_rows($generate) < 1) {
$sql = "INSERT INTO password_reset (code,email) VALUES ('$code','$email')";
} else {
$sql = "UPDATE password_reset SET code='$code' WHERE email='$email'";
}
if ($conn->query($sql) == TRUE) {
echo "Reset password has been emailed to you";
} else {
}
} else {
echo "Could not find email in the system.";
}
}
Thank you #Bleach and #ivanivan for your comments. Both your answers helped out. Here's the working result. Making a variable false outside of the loop, gave me the answer I was looking for.
$sql_1 = "SELECT * FROM password_reset WHERE email='$email'";
$sql_2 = "SELECT * FROM barn_users WHERE email='$email'";
$generate = mysqli_query($conn, $sql_1);
$searchEmail = mysqli_query($conn, $sql_2);
$found = false;
while($row = mysqli_fetch_array($searchEmail)) {
$found = true;
if(mysqli_num_rows($searchEmail) > 0) {
if (mysqli_num_rows($generate) > 1) {
} else if (mysqli_num_rows($generate) < 1) {
$sql = "INSERT INTO password_reset (code,email) VALUES ('$code','$email')";
} else {
$sql = "UPDATE password_reset SET code='$code' WHERE email='$email'";
}
if ($conn->query($sql) == TRUE) {
echo "Reset password has been emailed to you";
} else {
}
} else {
}
}
if ($found == false) {
echo "Sorry, that email was not found in the system. Please try again.";
}

Php signup form doesn't work - Form just refreshes when input checks out requirement

The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}

MySQL `UPDATE` statement with an `IF` condition

I'm trying to create a MySQL UPDATE statement with an IF condition.
I would like to update the user's particulars if the email and username are not duplicate or found in database.
I'm stuck with this code:
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Check Email in Database
$query = mysqli_query($con,"SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_fetch_object($query);
if (strtolower(trim($query->email)) == strtolower(trim($em))
|| strtolower(trim($user->username)) == strtolower(trim($user))
) {
//next to condition username
} else {
$data_email = mysqli_query($con,"select email from user where em='".$em."'");
$total_email = mysqli_num_rows($data_email);
if($total_email > 0) {
echo "Email Not Available";
} else {
//next to condition username
}
}
//Check Username in Database
$data_us_user = mysqli_query($con,"select username from user where id_user='".$id."'");
$us_user = mysqli_fetch_object($data_us_user);
if (strtolower(trim($us_user->username))==strtolower(trim($user))) {
//next to query update
} else {
$data_username = mysqli_query($con,"select username from user where username='".$em."'");
$total_username = mysqli_num_rows($data_username);
if($total_username > 0) {
echo "Username Not Available";
} else {
//next to query update
}
} else {
//Finally Query Update
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
The following PHP script will check for
IF the user's updated email and updated username are the same
IF the user's new email and username is already in use by another user
IF both conditions are not met, the user's details will be updated
PHP code:
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Getting user' details in database
$query = mysqli_query($con, "SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_query($query);
//Query to find if email exists
$query2 = mysqli_query($con,"SELECT `email` from `user` WHERE em = '$em'");
$result2 = mysqli_num_rows($query2);
//Query to find if username exists
$query3 = mysqli_query($con,"SELECT `email` from `user` WHERE id_user = '$user");
$result3 = mysqli_num_rows($query3);
while ($row = mysqli_fetch_row($result)){
list($userfromdb, $emfromdb) = $row;
}
if (strtolower(trim($userfromdb)) == strtolower(trim($user))){
//will return true if user's username is the same before updating
echo 'Username cannot be the same!';
} else if(strtolower(trim($emfromdb)) == strtolower(trim($em))) {
//will return true if user's email is the same before updating
echo 'Email cannot be the same!';
} else if($result2 > 0) {
echo "Email Not Available";
} else if($result3 > 0) {
echo "Username Not Available";
} else {
//Finally Query Update
mysqli_query($con, "UPDATE `user` set username = '$user',em = '$em' WHERE id_user = '$id'");
//check if row updated successfully
$result4 = mysqli_affected_rows($con);
if ($result4 > 0) {
echo "Updated details successfully";
} else {
echo "An error occurred while updated details.";
}
}
?>
This should work, thanks!
If specifying column related message is not the concern,
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
$data_us_em = mysqli_query($con,"select count(email) as count from user where id_user='".$id."' OR em='".$em."' OR username='".$em."'");
if($data_us_em)
{
$us_em = mysqli_fetch_assoc($data_us_em);
$count=$us_em['count'];
if($count)
{
echo 'Can not update';
}else
{
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
}
?>
$data_user= mysqli_query($con,"select email,username from user where id_user='".$id."'");
$userdetail = mysqli_fetch_object($data_user);
if (strtolower(trim($userdetail->email))==strtolower(trim($em)) || strtolower(trim($userdetail->username))==strtolower(trim($user)))
{
return "error message";
}else{
//your update method here
}

I need to check my db to see if a username or email is already in use

I've started a thread or two so far but nothing has got resolved. I'm not able to use the mysqlnd because i'm using a shared hosting account with godaddy.
All i need to do is check if my email address and/or username is in use; if they are in use throw and error, if not.. all is well.
Here is my code:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}
else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
bind_result() does not work.
Change your sql statement to the following:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = '".mysqli_real_escape_string($_POST['username'])."' OR email = '".mysqli_real_escape_string($email)."'";

PHP code show still with error even if all input are correct. What's wrong with my code?

I'm making a simple registration system in php however, even if i enter all correct details, it doesn't go to the database, it still echo that withError = 1 even if all entries are correct. Here is my php code.
<?php
if($submit)
{
if ($fullname && $email && $username && $password && $conPassword)
{
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email))
{
$query1 = "SELECT Email FROM tbl_userAccounts WHERE Email='$email'";
$result1 = mysqli_query($mysqli,$query1) or die(mysqli_error());
if (mysqli_num_rows($result1) < 0)
echo "email is already used. ";
$withError = true;
}
else
{
echo "invalid email address. ";
$withError = true;
}
if (strlen($username) < $charMinimum)
{
echo "minimum of 6 characters for username. ";
$withError = true;
}
else
{
$query2 = "SELECT Username FROM tbl_userAccounts WHERE Username='$username'";
$result2 = mysqli_query($mysqli,$query2) or die(mysqli_error());
if (mysqli_num_rows($result2) < 0)
{
echo "username is already used. ";
$withError = true;
}
}
if($password == $conPassword)
{
echo $withError;
if($withError == false)
{
if (strlen($password) < $charMinimum)
{
echo "minimum of 6 characters for password. ";
$withError = true;
}
else
{
$query3 = "INSERT INTO tbl_userAccounts VALUES ('', '$fullname', '$username', '$password','$date', '$email')";
$result3 = mysqli_query($mysqli,$query3) or die(mysqli_error());
if($result3 && $withError == false)
echo "account has been successfully registered!";
else
echo "failed registration. ";
}
}
}
else
{
echo "passwords do not match. ";
$withError = true;
}
}
}
else
{
echo "fill out all fields. ";
$withError = true;
}
?>
You forgot to wrap the nested IF statement.
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email))
{
$query1 = "SELECT Email FROM tbl_userAccounts WHERE Email='$email'";
$result1 = mysqli_query($mysqli,$query1) or die(mysqli_error());
if (mysqli_num_rows($result1) < 0) {
echo "email is already used. ";
$withError = true;
}
}
if (mysqli_num_rows($result1) < 0)
{
echo "email is already used. ";
$withError = true;
}
You forgot the curly bracket

Categories