User authentication PHP/SQL

First of all. I'm new to both PHP/SQL and StackOverflow, so I'm sorry if my post is weird. I'm having a hard time figuring out what is wrong with my code. I have registered several users (each with a password ofc), but i only get login failed. Is it my if that is wrong?

Thank you.

<?php

session_start();

    //Connecting and choosing DB
    $connection = mysql_connect("link", "user", "pw");           
    mysql_select_db("user", $connection); 

    $username = mysql_real_escape_string($_POST['brukernavn']);
    $password = mysql_real_escape_string($_POST['passord']);


    // Check the users input against the DB.
    $sql = "SELECT * FROM brukere WHERE brukernavn = '$username' AND passord = '$password'";
    $result = mysql_query($sql) or die ("Unable to verify user because " . mysql_error());

    $row = mysql_fetch_assoc($result);

    if($row['total'] == 1)

    {
        $_SESSION['loggedIn'] = "true";
        header("Location: insertlink");
    }
    else
    {
        $_SESSION['loggedIn'] = "false";
        echo "<p>Login failed, username or password incorrect.</p>";
    }

?>

Upvotes: 0

Views: 81

Answers (1)

lxg
lxg

Reputation: 13127

There is no total field in the array returned by mysql_fetch_assoc().

If you want to know the number of results, use the count function:

if(count($rows) === 1)
…

Btw, as already mentioned:

  1. mysql_* is deprecated, use mysqli_* or PDO.
  2. You're storing clear-text passwords in your database, which is very bad. Please read about hashing and salting stored passwords.

Upvotes: 3

Related Questions