简体   繁体   中英

My if / else statement doesnt work for my custom php login script

Somehow my conditional simply doesnt work. Once I click the button on my login form which is set to "post" and has the action defined as the below login script I only get directed to the script but not redirected as defined in my conditional statement. What is wrong with my code?

session_start();

$servername = "localhost";
$username = "root";
$password = "";
$database = "project";

$connection = mysqli_connect($servername, $username, $password, $database) or exit(header("location:maintenance.php"));

function login_check() {

    global $connection;

    $name = $_POST['name'];
    $password = $_POST['password'];

    $prepared = mysqli_stmt_init($connection);
    $request = mysqli_stmt_prepare($prepared, "SELECT id FROM members WHERE name = ? AND password = ?");
    mysqli_stmt_bind_param($prepared, "ss", $name, $password);
    $result= mysqli_stmt_bind_result($request);
    $rows_counter = mysqli_num_rows($result);
    mysqli_stmt_close($prepared);

    if ($rows_counter > 0) {
        $_SESSION['member'] = $name;
        header("location:../../success.php");
    }
    else {
        header("location:../../relogin.php");
    }
}

Here is my input and approach to your code.

First of all before writing a solution and tell to much, it is always a good practice to make step by step code troubleshooting.

Before going and building a complete login system and put if statement or make prepare statement with inputs etc.

Make your solution in small working chops and put the puzzle together.

You question was focused on if statement and most of the help and answer was also focused on if statement which is nice, but the problem was not there.

I removed the if statement and a lot and just focused to see if I get some thing returned, I did not .

You $result= mysqli_stmt_bind_result($request); missed arguments, when that fixed, the next line missed also something else. I already there quit debugging.

I have rewrite your code and it works, what I did I have redefined the naming of variable so they are crystal clear to understand what is name , call it username , database username call it dbUser or dbUsername etc.

And if you want to check your code returning some thing or not, use var_dump($someVariable) .

Last thing, before making a post form, you could create a dummy username and password in your database and inject that directly in your code like, just to see if every thing is working, and then move to your form:

$username = "user1";
$password = "1234";

The solution I did is just to demonstrate how to do it and not necessarily representation of the best logic, but it is up to you to find the correct logic and all depends on your strategy.

Here is my suggestion:

<?php
session_start();

$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "product";

$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

// Check connection
if ($connection->connect_error)
{
    header("location:maintenance.php");
    exit();
    // or for debugging, activate following line
    //die("Connection failed: " . $connection->connect_error);
}

$username = $_POST['username'];
$password = $_POST['password'];

//if username and password empty stop login
if (!$username || !$password)
{
    //do something, die is only example
    die ("Not all the fields were filled in");
} else
{
    login_check($username, $password);
}

function login_check($username, $password)
{
    global $connection;

    //sql statements is corrected, change field name to username
    $sql = "SELECT * FROM `members` WHERE `username` = ? AND `password` = ?";
    $stmt = $connection->prepare($sql);
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $output = $stmt->get_result();
    $row = $output->fetch_array(MYSQLI_NUM);
    $stmt->close();
    //print what comes out in $row
    //print_r($row);

    //check if $row has data
    if ($row)
    {
        echo "success do something";
        $_SESSION['member'] = $username;
    } else
    {
        echo "fail do something";
    }
}

Always, always, always put exit() after header redirect call. Even in that case, it might solve your issue.

header("location:../../success.php");
exit();

Why?

After defining the function login_check() , you should also call it (if the conditions are right):

function login_check() {
    // your implementation as above
}

if (isset($_POST['name']) && isset($_POST['password'])) {
    login_check();  // actually call the function
}

As a side note, it is good practice to also explicetely close the connection before redirecting.

Edit

as KhomeHoly comments, only call the function when necessary...

You need to call your functions if you define them. Not doing so is like building a room within a new house but forgetting the door. It's there, but nobody can use or access it.

So what you need to do is the following:

// your script as it is right now

if (isset($_POST['name']) && isset($_POST['password'])) {
    login_check();  // actually call the function
}

With isset() you check if the certain $_POST parameters are set, but not validated. You should at least do a basic validation of the data to see if they are correct!

Something like this would work, depends on your requirements

if (isset($_POST['name']) && strlen($_POST['name') >= 4 && isset($_POST['password']) && strlen($_POST['password']) >= 4) {
    login_check();  // actually call the function
}

The code above would check if those paramters are set and check if name and password are at least 4 characters long. (I wouldn't accept usernames lower than 4 chars personally, passwords should be at least 8 for me)

Now of course this misses an correct error reporting and all that stuff, but I think that should give you the basic idea based on your quesiton.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM