Click the button, save the data and go to next php page - php

I don't know what is the problem. After i click the button, it only the data into database but will not go to next php page. Help me find out what is problems. Thank you.
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
header('Location: mcreport.php');
if($AddMCResult)
echo "<script>alert('Record Added.');</script>";
}
//button
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit"/>

Try this
<?php
if(isset($_POST['btnSubmit']))
{
$txtName=$_POST['txtName'];
$txtFrom=$_POST['txtFrom'];
$txtTo=$_POST['txtTo'];
$txtReason=$_POST['txtReason'];
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('$txtName','$txtFrom','$txtTo','$txtReason')";
$AddMCResult = mysql_query($AddMCQ,$link);
if($AddMCResult)
{
echo "<script language=\"JavaScript\">\n";
echo "alert('Record Added.');\n";
echo "window.location='mcreport.php'";
echo "</script>";
}
}
?>

Your "Problem" is the result in $AddMCResult
After your have use header('Location: mcreport.php');
Your Script redirect to the given url and the result in $AddMCResult is not given any more
So a quick and dirty solution could be
if(isset($_POST['btnSubmit'])){
$AddMCQ = "INSERT INTO tblmc(Name,FromDate,ToDate,Reason) VALUES('".strtoupper($_POST['txtName'])."','".$_POST['txtFrom']."','".$_POST['txtTo']."','".strtoupper($_POST['txtReason'])."')";
$AddMCResult = mysql_query($AddMCQ,$link);
$_SESSION['AddMCResult'] = $AddMCResult;
header('Location: mcreport.php');
}
AND on mcreport.php
if(isset($_SESSION['AddMCResult']) && $AddMCResult)
echo "<script>alert('Record Added.');</script>";
...
But check, that session_start() was called on both files ...

Check Carefully Table Name and Passing Parameters - Through one to another page - see get and post method-
<?php
include 'config.php';
$submit="submit";
$page = $_SERVER['PHP_SELF'];
$sl_no=$_POST['sl-no'];
$f_name=$_POST['f_name'];
$l_name=$_POST['l_name'];
if($submit)
{
$sql = "INSERT INTO table_name(sl_no,f_name,l_name) values('$sl_no','$f_name','$l_name')";
$result = mysql_query($sql);
echo "Thank you! Information entered.\n";
}
else
{
echo "There Is Something Going Wrong While Insertion";
header('Location: error.php');
}

After your header put die() like
header('Location: mcreport.php');
die();
And better you use Absolute urls.Also you can use exit() instead of die().

Related

Echo success message after submitted form but before redirect and exit

Don't know how long i have worked on this, but nothing looks to be working. All i want to do is output a success message before it redirects and exits.
This is what i got to check for success/fail to the database
$sql = ("INSERT INTO test3 (test1, betvalue, bookmaker, status, aktiv) VALUES ('$bettype', '$betvalue', '$bookmaker', '$status', '$aktiv')");
$result = mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) >0 ) {
echo "Wow it works"; <-- Not working
header("Location: nybonus.php");
exit;
} else {
echo ("<div class='alert alert-danger' role='alert'>" . $sql . "</div><div class='alert alert-danger' role='alert'>" . mysqli_error($conn) . "</div>");
}
It does not output any echo if it has be successful, i have tried making it sleep with correct flushing to try to output an messsage, but it does not work at all. Is there a better way to do it? Also can someone explain why it wont echo before the header and exit?
Could you achieve what you want by setting a session variable and checking for the state of that variable on reload:
$message = '';
if(isset($_SESSION['success'])) {
if($_SESSION['success'] == 'success') {
$message = 'Success';
}
}
$sql = ("INSERT INTO test3 (test1, betvalue, bookmaker, status, aktiv) VALUES ('$bettype', '$betvalue', '$bookmaker', '$status', '$aktiv')");
mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) > 0) {
$_SESSION['success'] = 'success';
header('Location: nybonus.php');
exit;
}
else {
$_SESSION['success'] = 'fail';
.....
}
<script>
$("#message").fadeOut(2000, function() {
$("#message").fadeIn(0, function() {
document.getElementById("message").innerHTML ="<br>";
});
});
</script>
<div id="message">
<?php echo $message; ?>
</div>
The problem is when you use the "header" it has to be first.
You can't print anything else to the screen before the header.
It's the same as when you're setting cookies.
So in your case you can't do the redirect with "header".
You could use a meta refresh.
<meta http-equiv="refresh" content="0; url=http://www.somewebsite.com">
The "content" is number of seconds to wait before doing refresh.
You'll have to explain what you're trying to accomplish more precisely... like step 1 do this step 2 do this and so on.
Previously I understood you had asked how to do a redirect after echoing a message.
So now explain more detail in steps what you're wanting to do and maybe I can help.
If you mean the user is one "page1" and they submit a form and then on the resulting page you want to display the message? Then redirect...
You would just need to make the form action be the same url path as the page they are currently on.
Do you follow me?

Write text with echo() after reloading page with header()

I have page called account_settings.php and it's consist of change password, change profile pic, change user details (name, bio etc.). My question is how to write message with echo() after redirecting page with header().
Something like this:
if (true)
{
Do_Some_MySQL();
header("Location: account_settings.php");
echo "Success!";
}
else
{
echo "Error!";
}
Thank you for all replies. ;-)
You can't actually do something after sending a Location header - it is impossible.
Instead, you could use $_SESSION array value to perform your task. Like:
if (true)
{
Do_Some_MySQL();
$_SESSION['message'] = 'Error!';
header("Location: account_settings.php");
}
else
{
echo "Error!";
}
And then on your account_setting.php:
<?php echo $_SESSION['message'] ?>
This would be nice if the account_settings.php is not the same page as you currently are. Otherwise, you could use the following code:
if (true)
{
Do_Some_MySQL();
$error = 'Success!';
header("Location: account_settings.php");
}
else
{
$error = "Error!";
}
And on the same page:
<?php if($error) echo $error; ?>
Also don't forget to include session_start() on both pages if you didn't it yet.
I would use a SESSION variable:
on redirect-page:
<?php
#session_start();
if(true){
$_SESSION['success'] = 1;
header("Location: account-settings.php");
}
?>
and on account-settings.php:
<?php
#session_start();
if(isset($_SESSION['success'])){
echo "Success!";
unset($_SESSION['success']);
}
You cannot echo anything after you just redirected. The browser is already processing the request to redirect to another page, so it doesn't bother about displaying the message anymore. What you seem to be looking for is something called flash message. You can set a temporary message in the session and have it display on the new page. For example, in your account_settings.php page:
// Make sure you have an actual session
if (!session_id()) {
session_start();
}
if (true) {
Do_Some_MySQL();
$_SESSION['flashMessage'] = 'Success!';
header('Location: account_settings.php');
}
Then in your template file for account_settings, check if there is any flash message and display it accordingly (and unset it to avoid a loop):
if (isset($_SESSION['flashMessage'])) {
echo $_SESSION['flashMessage'];
unset($_SESSION['flashMessage']);
}
These people are correct...you can't send headers after a redirect. Although I think this would be a beneficial alternative. To send a GET request in your header and process it on the receiving page. They are suggesting to use $_SESSION vars, but you can use GET vars. Ex:
if (true)
{
//Do_Some_MySQL();
header("Location: account_settings.php?message=success");
//above has GET var message = Success
}
else
{
header("Location: account_settings.php?message=error");
}
On your account_settings.php page have this code:
if (isset($_GET['message'])) {
$message = $_GET['message'];
if ($message == "success") {
echo "Success";
} else {
echo "Error";
}
}
This removes the need of CONSTANT SESSION vars. and gives you plenty of flexibility.
header("Location: account_settings.php?message=No%20results%20found");
//%20 are URL spaces. I don't know if these are necessary.
If you need you can add more then one.
header("Location: account_settings.php?message=error&reason=No%20Results&timestamp=" . Date());
then account_settings.php can be:
if (isset($_GET['message'])) {
$message = $_GET['message'];
$reason = $_GET['reason'];
$time = $_GET['timestamp'];
if ($message == "success") {
echo "Success";
} else {
echo "Error: <br/>";
echo "Reason: $reason";
}
}
But remember GET exposes your messages in the browsers URL. So DON'T send sensitive information unless you secure it. Hope this helps.

header location not working but stuck in page

so I have a button
<input type="button" value="add" onclick="document.location.href='add.php?myUcode=<?=$row['ucode'];?>'" />
to another page (let's call it Page1). in Page1, I want to add a value to $_SESSION['employees'] and then redirect it back to home.php. but when I click the button, it gets stuck in add.php. there is no echo or whitespace before I call the Header method. now I have no idea what is wrong with my code :
<?php
session_start();
if ($_POST['tambah_ucode']) {
if (isset($_SESSION['jum_petugas'])) {
$_SESSION['jum_petugas'] = 1;
$ctr = $_SESSION['jum_petugas'];
} else {
$ctr = $_SESSION['jum_petugas'];
$ctr++;
$_SESSION['jum_petugas'] = $ctr;
}
$_SESSION['ucode_petugas'][$ctr] = $_POST['tambah_ucode'];
header('Location: localhost/hrm2.1/lembur_add.php');
}
?>
Try this,
header('Location: lembur_add.php');
exit;
OR
header('Location: http://localhost/hrm2.1/lembur_add.php');
exit;
header('location:localhost/hrm2.1/lembur_add.php')
without space
Try the following
header('Location:http://localhost/hrm2.1/lembur_add.php');
Instead of header(...), try
echo "<script type='text/javascript'> document.location = 'yourLocation'; </script>";

php header() function won't redirect

I'm trying to post data from a form with insert.php as the action. However, I cannot redirect back to the index.php once the data has posted to the database.
I've searched through the following sites to find the answer:
Trip Wire Magazine
Daniweb
as well as ten stackoverflow questions on the subject.
Here is the code for the insert.php file:
<?php
include 'connect.php';
$id = $_POST['id'];
$idea = mysql_real_escape_string($_POST['new_idea']);
if(!$_POST['submit']) {
echo "Please fill out the form!";
header('Location: index.php');
} else {
mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error());
echo "Idea has been added!";
header('Location: index.php');
}?>
From what I've gathered, the header() function won't execute if there's text output before it. I've tried this function without the echo "Idea has been added!"; and echo "Please fill out the form!";, but I still don't get a redirect.
Thanks in advance for your advice.
-MF
From PHP documentation :
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
And in your case, you are using echo before header()
work around method : use ob_start() at the top of the page
other method : Please omit any white space before starting <?php or after ?> in the page
and also use exit() just after header()
Try this
<?php
include 'connect.php';
$id = $_POST['id'];
$idea = mysql_real_escape_string($_POST['new_idea']);
if(!$_POST['submit']) {
$message = "Please fill out the form!";
header('Location: index.php?message='.$message); exit;
} else {
mysql_query("INSERT INTO user_idea (`id`, `idea`, `time_created`) VALUES(NULL, '$idea', NULL)") or die(mysql_error());
$message = "Idea has been added!";
header('Location: index.php?message='.$message); exit;
}?>
Pass the error message to index.php and display it there.
Don't print your output before header(). Store your data into session or pass it through URL.
Try this will surely help you .

Refresh button on Browser

I have a simple coding problem. I try to create a page with a textbox and a share button.
When the user clicks the share button the text in the textbox get inserted as string into the database table named "posts".
I use the following code.
<?php
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
else
echo "<script type='text/javascript'>alert('some error')</script>";
}
else
{
?>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
Status : <input type = "text" name ="status">
<input type = "submit" name ="share">
</form>
<?php
}
This solution works fine but there is a problem when the user refreshes the page. The browser will show a message window asking for resend the information, which will submit the post to the table again. Then the same entry is in the table twice.
I want the user to stay on the same page after submitting. But a page refresh should not show the message window or send the information again.
Thanks in advance!
Redirect the user after he shares, use redirect
header('Location: whatever.php');
exit;
Use this :
<?php
if(isset($_POST['share'])) {
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res) {
?>
<script type='text/javascript'>alert('Posted successfully')</script>
<?php
header('Location: whatever.php');
exit;
} else {
?>
<script type='text/javascript'>alert('some error')</script>
<?php
header('Location: whatever.php');
exit;
}
}
?>
And btw better don't alert the users using javascript
AND DO USE BRACES AROUND IF ELSE
P.S : You Can Also Redirect An User Using JavaScript window.location
Header Reference
It's called "redirect-after-post": After you received the post request and did something useful with it, you redirect the user (usually) back to theire own post, or whatever.
You can try doing redirect just after your logic saving the post is done.
header("location: $my_page");
exit();
Set variable $your_page with the name of page which contains your code
$my_page = 'yourpage.php';
This should work:
$my_page = 'your_page.php'
if(isset($_POST['share']))
{
$status = $_POST['status'];
$res = mysql_query("insert into `posts`(postid,username,post,pointscollected) values('','$username','$status','')");
if($res)
{
echo "<script type='text/javascript'>alert('Posted successfully')</script>";
header("location: $my_page");
exit();
}
else
{
echo "<script type='text/javascript'>alert('some error')</script>";
header("location: $my_page");
exit();
}
}
Right after you have finished inserting your query and everything, change to another page using:
<?php
header('Location: /path/to/yourotherpage.php');
exit();
?>
What this does, is it is a redirect to another page, which removes all POST data from the browser's 'memory' of the page.
On that page, you write something like 'Your stuff has been submitted and recorded', whatever you want, your choice.
If your user refreshes on that page, nothing will be inserted at all.
That should work.

Categories