Header function is not working in switch case in

Issue

I’m working on like dislike rating system in PHP.

// if user clicks like or dislike button
if (isset($_POST['action'])) {
    if (isset($_SESSION['uid'])) {
        $action = $_POST['action'];
        switch ($action) {
            case 'like':
                $sql = "INSERT INTO rating (uid, pid, action) 
                VALUES ($uid, $pid, 'like') 
                ON DUPLICATE KEY UPDATE action='like'";
                break;
            case 'dislike':
                $sql = "INSERT INTO rating (uid, pid, action) 
               VALUES ($uid, $pid, 'dislike') 
                ON DUPLICATE KEY UPDATE action='dislike'";
                break;
            case 'unlike':
                $sql = "DELETE FROM rating WHERE uid=$uid AND pid=$pid";
                break;
            case 'undislike':
                $sql = "DELETE FROM rating WHERE uid=$uid AND pid=$pid";
                break;
            default:
                break;
        }
        // execute query to effect changes in the database ...
        mysqli_query($con, $sql);
        echo getRating($pid);
        exit(0);
    } else {
        header("location:login.php");
    }
}

If a user is logged in then it’s working fine but when user is not logged in then the else part which is including PHP header function is not working and not showing any error and not even inserting data into the database.

If there is another alternative then please do tell

Solution

Cannot guarantee this is the answer exactly — will remove if not useful

I think it could be malformed header. Capitalization and space. header("location:login.php") should be

header("Location: login.php");

check the manual here for header Location examples

see MDN for a clear example of header syntax

EDIT:
Since you said it still didn’t work then it is likely that your SESSION is always set. You should debug your SESSION handling code.

Answered By – GUEST

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published