Home > Back-end >  Cant fix my if-else condition in login.php
Cant fix my if-else condition in login.php

Time:11-02

I have created a condition to check if name and password are correct the only issue here is when i test it it goes complete the opposite of what i want. It doesnt matter if i put it right or wrong the message will always be "You have successfuly logged in". Im using PDO just to know

<?php
  include('connection.php');

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

  $data = $_POST;
 
  $statment = $connection->prepare('SELECT * FROM registration WHERE name = :name AND password = :password');

  if($statment){
    $result = $statment->execute([
        ':name' => $data['name'],
        ':password' => $data['password']
    ]);
   } 



  if($data['name'] == $name && $data['password'] == $password){
       echo 'You have successfuly logged in';
  }else {
       die('Incorrect username or password');
  } 


 
?>

CodePudding user response:

You have made your script overly complicated .. The easiest way is to bind and execute .. Then you can simply check if there are any rows, and THEN compare with your data array created from the executed statement.

<?php
    include('connection.php');

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

    $statment = $connection->prepare("SELECT name, password FROM registration 
                                       WHERE name = ? AND password = ?");
    $statment ->bind_param("ss", $name, $password);
    $statment ->execute();
    $result = $stmt->get_result();

   if ($result ->num_rows > 0) {
       $data = $result->fetch_array();
   }else{
       echo "No results found";
   }

   if($data['name'] == $name && $data['password'] == $password){
       echo 'You have successfuly logged in';
  }else {
       die('Incorrect username or password');
  } 
?>

(bear in mind I wrote that freehand, and it has not been tested or debugged, but the principals are there)

ON A SIDE NOTE

That being said .. You should never be storing passwords in a open "text" field. You should be encrypting them. The easiest way is to use bcrypt to build out a hash:

$options = [
   'cost' => 12,
];

$newPass =  password_hash($pass, PASSWORD_BCRYPT, $options);

And store that in your database .. Then you can compare it like so ..

 if (password_verify($pss, $pwdCheck)

$pss being what was sent in from the form .. and $pwdCheck being the hash you SELECTED from the database -- Brought into your current code set, would look something like:

if($data['name'] == $name && password_verify($password, $data['password']){
  • Related