2

I just started working with php and I'm not really good at it.I need to verify my user's password and username after they passed that I want to start an session with that users user_id. But everytime I try to echo the user_id I just get nothing back. hope someone can help me with this. is my code:

<?php
 require_once "config.php";
 $username = $_POST['username'];
 $password = $_POST['password'];
 $hash = password_hash($password, PASSWORD_DEFAULT);
 if (strlen($username) > 0 && strlen($hash) > 0){
  $query = "SELECT user_id FROM keep_user WHERE username =    '$username' AND password = '$hash'";
  $result = mysqli_query($conn , $query);
  if($conn->query($query) == TRUE){
     if(password_verify($password, $hash)){
         session_start();
         $_SESSION['user_id'] = $user_id;
         echo $user_id;
         echo "succes";
     }else{
         echo "error-1".$conn->error;
     } 
   }else{
        echo "error-2".$conn->error;
        exit;
   }
 }else{
     echo "error".$conn->error;
     exit;
 }
?>

It does echo success so I am guessing that part is good but why can't retrieve user_id?

pah
  • 4,700
  • 6
  • 28
  • 37
djamaile
  • 695
  • 3
  • 12
  • 30

1 Answers1

2

Problem is not with password_verify function . Problem is with mysqli_query because you execute your query two times

 $result = mysqli_query($conn , $query);// first time
  if($conn->query($query) == TRUE){// second time

Just comment or remove $result = mysqli_query($conn , $query);// first time

To get user id form query you need to fetch it as

if ($result = $conn->query($query)) {
    /* fetch associative array */
    $row = $result->fetch_assoc() ;
    $user_id=$row["user_id"];
    $_SESSION['user_id'] = $user_id;

}

And session_start(); at the top of your page.

You script is open for sql injection Read How can I prevent SQL injection in PHP? to prevent it

Community
  • 1
  • 1
Saty
  • 22,443
  • 7
  • 33
  • 51