pimmen
pimmen

Reputation: 402

SQL returns true even when should return false

I have a "set password" site where you can set your password only if you do not currently possess one. I therefore have a SQL query that selects the username and password we will work with only if the email matches the one in the database AND the password is NULL. If this one returns false, the PHP-script should not do anything other than echo "Password or username is not valid". It also does other things, like check the length of the password and if it was confirmed, but this is the one which is messing up. Any thoughts?

This is my PHP-code so far:

<?php
session_start();
require 'connect.inc.php';
include 'core.php';
ob_start();
?>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<?php
echo "
            <form action='update.php' method='post'>
            Ange din E-post.<br>
            E-post: <input type='text' name='mail' /><br>
            Ange ditt lösenord, minst sex tecken.<br>
            Lösenord: <input type='password' name='pass1' /><br>
            Bekräfta: <input type='password' name='pass2' /><br>
            <input type='submit' value='Godkänn'/><br>";

if(isset($_POST['pass1'])&&isset($_POST['pass2']))
            {

                $email = $_POST['mail'];
                $query = "SELECT login_id, pass FROM users WHERE (email = '$email') AND (pass IS NULL)";
                $query_run = sqlsrv_query( $link, $query);



                if(($_POST['pass1'] == $_POST['pass2']) && !empty($_POST['pass2']) && $query_run && (strlen($_POST['pass2'])>5))
                {
                    $row = sqlsrv_fetch_array($query_run, SQLSRV_FETCH_ASSOC);

                    $id = $row['login_id'];
                    $_SESSION['id'] = $id;

                    $pass = $_POST['pass1'];

                    $query2 = "UPDATE users SET pass = '$pass' WHERE login_id = '$id'";
                    sqlsrv_query( $link, $query2);

                    $next = "https://localhost/title_choice.php";
                    header('Location: '.$next);
                }else
                {
                    echo "Lösenorden matchar ej, eller E-post ogiltig! Var god ange dem igen!";
                }
            }

ob_end_flush();
?>

Upvotes: 1

Views: 115

Answers (1)

hichris123
hichris123

Reputation: 10223

It looks like what you're doing is checking if the query has ran. This statement will check if the query ran:

if(($_POST['pass1'] == $_POST['pass2']) && !empty($_POST['pass2']) && $query_run && (strlen($_POST['pass2'])>5))

Instead, you should be checking if the query returns nothing. You can use sqlsrv_has_rows like this:

$rows = sqlsrv_has_rows($query_run);
if(($_POST['pass1'] == $_POST['pass2']) && !empty($_POST['pass2']) && $rows && (strlen($_POST['pass2'])>5))
{
    //rest of your code here
}
else{
    //no rows returned
}

Upvotes: 2

Related Questions