I can't seem to get this else statement to work in php

59 views Asked by At
<?php 

session_start();

$link = mysqli_connect(database connection info);

if (mysqli_connect_error()) {
    echo "Could not connect to database";
    die;
}

if (isset($_POST['submit'])) {

    $query = "SELECT * FROM users WHERE email = '".$_POST['email']."'";

    $result = mysqli_query($link, $query);

    if ($row = mysqli_fetch_array($result)) {

        if ($_POST['email'] == $row['email'] && password_verify($_POST['password'], $row['password']))
        {
                $success .= "We're in baby";
        } else {
            $error .= "didn't work boi";
        }


    }

}

?>

Basically for some reason the else statement in this code

        if ($_POST['email'] == $row['email'] && password_verify($_POST['password'], $row['password']))
        {
                $success .= "We're in baby";
        } else {
            $error .= "send help";
        }

is not working at all. The problem isn't within the error variable as echo does not work either. I can't get the else statement to output any response whatsoever if the original if statement returns false. The if statement executes perfectly fine if it returns true!

Please help.

2

There are 2 answers

3
Rotimi On BEST ANSWER

As per my comment, to get the else statement executed, enter a valid email address from your database and a wrong password. That should get to the else statement.

To echo $error, define $error = ''; at the top of the script and then add

echo $error;  //Below the closing `}` of the `if($row....) ` statement 

Also your query is not safe at all. You're directly injecting a variable that can be easily manipulated by anyone. You should never trust such. Hence why we have prepared statements. They help prevent SQL injection attacks as well as those pesky quoting issues. Visit the link below for a tutorial on how to use them with the mysqli_ API.

https://phpdelusions.net/mysqli

0
astax On

Add an else part for the if ($row = mysqli_fetch_array($result)) - perhaps your query fails or the specified email doesn't exist in the db.

The condition $_POST['email'] == $row['email'] is useless as it's already part of the SQL statement.

Also, important(!): your code is vulnerable to SQL injection. Do not put unescaped values from POST to an SQL query.