I learned something interesting today. I am finishing up writing a blogging application and I wanted to transfer either a success or error message after a post was created. I was using the following code:
PHP:
-
-
if ($conn->num_rows == 0) {
-
$_SESSION['error'] = true;
-
$_SESSION['message'] = "Your message failed. Please contact the administrator";
-
} else {
-
$_SESSION['success'] = true;
-
$_SESSION['message'] = "Your message titled <i>$blog_title</i> was successfully created.";
-
But for some reason the session variables were not transfering to the index.php page. I Googled my problem and come to find out
PHP:
gets executed so fast that the session doesn't have a chance to set the variables. The solution is to use session_write_close();. This forces session data to be saved before the browser changes to the new page. Now my code looks like:
PHP:
-
-
if ($conn->num_rows == 0) {
-
$_SESSION['error'] = "Create New Message Failed";
-
$_SESSION['message'] = "Your message failed. Please contact the administrator";
-
} else {
-
$_SESSION['success'] = "Create New Message Success";
-
$_SESSION['message'] = "Your message titled <i>$blog_title</i> was successfully created.";
-
Works perfectly!