else function is not wroking even query fails

This is the code where this used to verify the token by getting it from url and matching it with databse. and when matches it updates a db field and gives a alert that account is verified according to code. It works good. but when url token is wrong and it doesnt updates databse field but still gives same alert that account is verified. but it should use that else fumction. But still it uses that if function. What is the reason behind this error?

session_start();

include 'partials/_dbconnect.php';
if(isset($_GET['token'])){
    $token = $_GET['token'];
  
    $updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
    $query = mysqli_query($conn, $updatequery);

    if($query){
        echo '<script>alert("Your account is verified successfully. Please login now. !")</script>'; 
        echo '<script> window.location.href = "/login.php"</script>';
    }
    
else{
        echo '<script>alert("This link is not valid. Acoount verification failed !")</script>'; 
        echo '<script> window.location.href = "/index.php"</script>';
}

} 
    


?>``
`

>Solution :

$query will return as true as long as the query executed successfully. You aren’t matching the token at all. You’re updating it. If the token doesn’t match, the database doesn’t update, but the query itself still returns true, that 0 rows were updated.

What you need to do is check if the token exists in the database first. If it does exist, then update it. Something like this:

    if(isset($_GET['token'])){
        $token = $_GET['token'];

        $checkquery ="SELECT `token` FROM `users` WHERE `users`.`token` = '$token' " ;
        $result = mysqli_query($conn, $checkquery);
        if(mysqli_num_rows($result) >0){
            $updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
            $query = mysqli_query($conn, $updatequery);
            echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
            echo '<script> window.location.href = "/login.php"</script>';
        }
        else{
            echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
            echo '<script> window.location.href = "/index.php"</script>';
        }
        
    }

Leave a Reply