Reputation: 752
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?
Upvotes: 2
Views: 87
Reputation: 22532
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
Upvotes: 2