Jump to content

Not sure how to pass a $msg variable to the next page


simcoweb

Recommended Posts

Jusssssst a bit rusty since i've been designing more than coding lately. Here's what I have:

 

I'm parsing a form to insert data into mysql, no problem. Then, after insertion, I want it to redirect to another page. I'm using the header() function for this. But, I have an array() that will contain a message (tucked into a variable called $msg) that I want displayed on that following page. Here's my code:

 

<?php

/**
* @author rockmetal
* @copyright 2008
* News insertion and display script
*/
include('db_config.php');
if(isset($_POST['submitted'])){
$msg = array();
// let us clean our input
$title = stripslashes($_POST['title']);
$today = date("F j,Y");
$summary = stripslashes($_POST['summary']);
$news = stripslashes($_POST['news']);

// insert into database

$query = "INSERT INTO news (title, today, summary, news) VALUES ('$title', '$today', '$summary', '$news')";
$results = mysql_query($query) or die(mysql_error());
$affrows = mysql_affected_rows($dbc);
if($affrows == 1){
$msg = "The news item was inserted successfully in the database";
header('Location: addnews.php');
} else {
$msg = "Unfortunately there was a problem inserting the news item into the database. Please retry";
header('Location: addnews.php');
}
}
?>

 

It redirects fine but no $msg displayed. Here's the bit of code on the receiving page that is set to display the $msg:

 

if(!empty($msg)){
foreach($msg as $error){
	echo "<span class='bodytext' color='red'>$error</span>\n";
}
}

 

Should this message be passed in the header() function? Or, in a 'session' parameter? A little guidance, puhleeeeez...thanks! :)

You do realize you declare $msg as an array, but then you overwrite it as a string. So when you do pass it on, you'll get a warning of some kind from foreach() saying that it expects argument 1 to be an array.

 

To pass it though, both pages should have this at the top:

session_start();

 

Then, above both header calls, place this:

$_SESSION['name_of_session_it_can_be_anything'] = $msg;

 

Then on the next page, to retrieve the session (make sure session_start() is at the top), you can do this:

 

$msg = $_SESSION['name_of_the_session'];

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.