Furkan yavuz February 2016

my query doesn't work

i am making an login script who is connected to a database but i get an

"Undefined variable: dbUsername in F:\xamp\register\login\functions.php on line 21"

I have further checked it and i saw that my query doesn't work can you guys help me?

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


 include_once("Connect.php");

    $username = strip_tags($_POST['username']);
    $password = strip_tags($_POST['password']);

      $sql = "SELECT id, username, password FROM login WHERE username = '$username' LIMIT 1";

      $query = mysqli_query($dbcon, $sql);

      if ($query) {
        $row = mysqli_fetch_row($query);
        $userId = $row[0];
        $dbUsername = $row[1];
        $dbPassword = $row[2];
      }
      if ($username == $dbUsername && $password == $dbPassword) {
        $_SESSION['username'] = $username;
        $_SESSION['id'] = $userId;
        header('location: login.php');
      } else {
        echo "incorrect username or password.";

      }
    }

Answers


Nikolai Engel February 2016

$dbUsername and $dbPassword are not set if $query is false.

Set $dbUsername = null; $dbPassword = null; before your if Statement.

Update your Where-Query to this:

"WHERE username = '. $username .'


devpro February 2016

You need to use your condition inside the if($query), but i dont think is there any need to recheck because you are already checking in Query WHERE username = $username. So i have modified your code as:

Modified Code:

  $sql = "SELECT id, username, password FROM login WHERE username = '$username' LIMIT 1";
  $query = mysqli_query($dbcon, $sql);
  if (!$query) {
    die(mysqli_error($dbcon));
  }
  else
  {
    $count = mysqli_num_rows($query); // check total no of rows

    if ($count > 0) 
    {
        session_start(); // start session
        $row = mysqli_fetch_row($query);
        $userId = $row[0]; // get userid from database
        $dbUsername = $row[1]; // get username from database
        $_SESSION['username'] = $dbUsername;
        $_SESSION['id'] = intval($userId);
        header('location: login.php');    
        die(); // using die() after header()
    }
    else{
        echo "incorrect username or password."; // if query not return anything print this.
    }  
  }

Post Status

Asked in February 2016
Viewed 1,846 times
Voted 5
Answered 2 times

Search




Leave an answer