Peter rosevelt Peter rosevelt - 2 months ago 13x
MySQL Question

Can't receive mysqli record with password verify

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:

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['user_id'] = $user_id;
echo $user_id;
echo "succes";
echo "error-1".$conn->error;
echo "error-2".$conn->error;
echo "error".$conn->error;

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


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() ;
    $_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