Mark Campbell
Mark Campbell

Reputation: 31

echo out message after sql function and after redirect?

I'm using this sql function to add and delete a user to/from favourites, if a user clicks the add to favourites button on another users profile then that will link to favourite.php and run the below script.

What i am trying to do, is after the sql has run and then redirected back to the users profile page, i want to echo out a message on that profile page that says user has been added to favourites (if a favourite has been inserted into the db) or user has been deleted from favourites (where a user has been deleted from favourites in the db).

CODE:

    <?php

    require_once('includes/session.php');
    require_once('includes/functions.php');
    require('includes/_config/connection.php');

    session_start();

        confirm_logged_in();

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


    }


    if (!isset($_GET['to']))
        exit('No user specified.');

    $user_id = $_GET['to'];

    mysql_query("INSERT INTO ptb_favorites (user_id, favorite_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")") 

    or mysql_query("DELETE FROM ptb_favorites WHERE user_id = ".$_SESSION['user_id']." AND favorite_id = ".$user_to_id.""); header("Location: {$_SERVER['HTTP_REFERER']}");

    #Method to go to previous page

    function goback()

    {
        header("Location: {$_SERVER['HTTP_REFERER']}fav=1");
        exit;
    }
    goback();

?>

I have already tried adding on the extension fav=1 on the redirect to echo out the message and have placed $_GET code in the profile page to display the error when the user lands back on the page:

<?
if (isset($_GET['fav']) && $_GET['fav'] == 1) {
            $message = "<div class=\"infobox-profile\"><strong>Added to Favourites.</strong>This user has been added to your favourites.</div>";
            echo "<a href=\"#\"><div class=\"infobox-close3\"></div></a>";

}
?>

Upvotes: 2

Views: 566

Answers (1)

Yanick Rochon
Yanick Rochon

Reputation: 53536

Use the $_SESSION object to pass messages across requests :

function goback()
{
    $_SESSION['flashmessage'] = "Some message";
    header("Location: {$_SERVER['HTTP_REFERER']}fav=1");
    exit;
}

Then, in your other script, just check for that variable.

session_start();

if (isset($_SESSION['flashmessage'])) {
    echo $_SESSION['flashmessage'];

    unset($_SESSION['flashmessage']);
}

Note : You should not rely on $_SERVER['HTTP_REFERER'] for the back value. I'm not sure how you manage your app, but a success should go to a success page, unless you explicitly set a forward URL. Just saying.

Upvotes: 1

Related Questions