What could be the query or what could be the solution of inserting values in database through html form via PHP but everytime I refresh the page the previously inserted value gets inserted again?
if (isset($_POST["insert1"])) {
$inrtno = $_POST["inrouteno"];
$instp = $_POST["instop"];
if ($inrtno !=''||$instp !='') {
$query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
Anytime you refresh the page you are resubmitting the POST variables, so the PHP still runs. Additionally, your query is in danger of SQL injection. Consider using PDO.
As stated previously (and for my own understanding), every time you refresh the page, the request is sent again. Mind me for forgetting that, thank you #ADyson.
So, a solution for that would be redirecting the user to the same form after the insertion is made.
Assuming this file would be test.php, for example:
if (isset($_POST["insert1"])) {
$inrtno = $_POST["inrouteno"];
$instp = $_POST["instop"];
if ($inrtno !=''||$instp !='') {
$query = mysqli_query($datacon,"REPLACE INTO `stops`(`sn`, `routeno`, `stop`) VALUES ('NULL','$inrtno','$instp')");
echo "<script type='text/javascript'>alert('Insertion Successful !!!')</script>";
sleep('3');
header('Location: /test.php');
exit();
} else {
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
When you reload the page the browser asks you to re-submit the request, so the value gets transferred again. So put a condition when you insert data that will check if the record already exists or not.
Related
I have a webpage that allows users to submit a query and get result in email.The user selects values for three variables and the email address. My problem is that everytime I refresh the page the form resubmits itself with old values and send the email (i.e I am not even clicking on submit query). I tried using $_POST=array() but it is still not working.
Here is my code:
<?php
if(isset($_POST['submit'])){
$varApp= $_POST['App'];
$varConfig = $_POST['Config'];
$varCtrType = $_POST['CtrType'];
$varEmail = $_POST['mailid'];
exec("/py $varApp $varConfig $varCtrType 2>&1",$output );
if ($output[8] == "Empty"){
echo "<div style ='font:22px Arial,tahoma,sans-serif;color:#ff0000'><br>No Data Available! <br></div>";
}
else {
exec(' printf "Please find attached the query result for following selection:\n\nApp: '.$varApp.' \nConfig: '.$varConfig.' \nCounter Type: '.$varCtrType.' \n\n Thanks! " | /bin/mail -s "Database Query Result" -a '.$output[8].' '.$varEmail.' 2>&1', $output2 );
echo "<div style ='font: 18px Arial,tahoma,sans-serif;color:#10ac84'><br><b> Please check your email for result !<b> <br>";
echo '<script language="javascript">';
echo 'alert("Please check your email for result! Submitted Query details: Selected App: '.$varAPP.' Configuration:")';
echo '</script>';
}
$_POST=array();
}
?>
</body>
I have not given the html part here.
So, everytime a user refreshes the page he gets an email again with previous session query results.
Any guidance here is highly appreciated.
Note: I am not using mail or pHPmailer here but that is not what I need to discuss here.
Thanks,
Taken from this answer:
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.
I have a form that posts to the same page because I need the values to display below after submit has been clicked, which it does. The problem is that as soon as the page is loaded, the php runs and sends the data to the database instantly, so it sends an empty value to the database since the user has not submitted anything.
$servername = "localhost";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO my_table (firstname)
VALUES (:firstname)");
$stmt->bindParam(':firstname', $firstname);
// insert a row
$firstname = $name;
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" id="nick-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
?>
I would like the $name variable to only get sent when the user hits submit, if possible.
"I would like the $name variable to only get sent when the user hits submit, if possible."
Use a conditional isset() with your submit button.
<?php
if(isset($_POST['submit']))
{
// code to execute
}
Sidenote: You could/should also add an !empty() on your inputs also, which is highly recommended in order to prevent empty submissions.
You could also implement a header upon successful submission to redirect to another page:
header('Location: http://www.example.com/');
exit; // avoid further execution of code, if any resides below that
http://php.net/manual/en/function.header.php
Just make sure you're not outputting before header if you plan on using it.
Here's an article on Stack about this:
How to fix "Headers already sent" error in PHP
There is also a good article on how to prevent multiple submits using sessions and tokens:
http://www.phpro.org/tutorials/Preventing-Multiple-Submits.html
Something I have used in the past with success which could be useful.
What you have is a possible checking clause with an if statement using
if (count($_POST) > 0) {
//code runs if POST is submitted data
if (!empty($_POST['name'])){
///process the name form field value
}
}
Which would solve your issue, BUT when the page is refreshed by the user, the refreshed page will also resubmit the POSTED data , this is why on database activity pages it is HIGHLY advisable to send the data to another page, and then once the data is saved, return the browser to the original page, so refreshing the original page does not resubmit the POSTED data
To illustrate further, make another PHP file called "save.php" and everything in the PHP tags ABOVE the <form> element, put in the save.php file, then set the form to goto save.php and at the bottom of the save.php set a header("location:formpage.php");die(); to return to the form.
You will still need a database call on the form page to display the desired output. But this will prevent resubmitting of data upon page refresh
You can use if :
if(isset($_POST['name']) && $_POST['name'] != null) {
// Your code
}
You should also check $_POST['submit'].
I have created a page where 'Job's' stored on a database are deleted.
On a page called
delete.php
the job to be deleted is selected.
The user is then directed to deleteaction.php where the job is deleted.
The user is then auto redirected back to
delete.php
This all works fine however once the user is returned to delte.php I would like a pop-up/ alert saying 'Job deleted'.
However if the user enters the page not from
deleteaction.php
then I dont want this pop-up to appear. I have tried to use sessions where a variable
$status
indicates if the user has just been directed to
deleteaction.php
and a job has been deleted.
Code on deleteaction.php:
session_start();
$id=$_GET['id'];
$sql= "DELETE FROM `Job` WHERE `Job`.`Job_Customer_id`='". $id."';";
$stmt=$dbh->query($sql);
$status = "deleted";
$_SESSION['delstat'] = $status;
header("Location:delete.php");
Code from delete.php:
session_start();
$status = $_SESSION['delstat'];
if ($status = "deleted"){
echo '<script language="javascript">';
echo 'alert("Job Deleted")';
echo '</script>';
}
else {
echo "No";
}
session_destroy();
........
The problem is the page delete.php always displays the alert that a job has been deleted every time the page is visited.
Not sure if its something wrong with my loop or the session use?
Thanks in advance!
You're presently assigning = instead of comparing == in
if ($status = "deleted")
being always TRUE
change that to
if ($status == "deleted")
This question already has an answer here:
Issue with uploading data into database
(1 answer)
Closed 8 years ago.
After successfully sending data to my database upon reloading the page it resubmit automatically again. Does anyone know why?
After successfully submitting data the first time, it clears the values inside the text field, but if i reload the page it automatically sends the previously filled data again into database.
To avoid it i have tried !empty condition. I have also tried unset $_POST.
My code looks like this:
if (isset($_POST['Posts'])) {
if (isset($_POST['t']) && isset($_POST['i']) && isset($_POST['P'])) {
$title = $_POST['t'];
$idea = $_POST['i'];
if (!empty($title) && !empty($idea)) {
$query = "INSERT INTO `updates` VALUES ('".mysql_real_escape_string($title)."')";
if ($query_run = mysql_query($query)) { }
else {
echo 'Sorry ,we could\'t register you at this time.Try again later';
}
}
}
}
try to add header at the end, example:
if (isset($_POST['Posts'])) {
//do something
//..do all post stuff
header('Location: thisPage.php'); //clears POST
}
After running the insert, redirect to a new page. Or you could even run a select to check if the data was just submitted, though you might want to put a time frame such as has it been inserted in the past 5 minutes or so. If it has not been inserted, then do the insert. If it was already inserted, either display the success message or a "this data has already been submitted" type answer.
Just trying to make a login page in php.. Here the if code is working but else code is not working.. it is also working if code.. instead of printing message..
here is the code:
session_start(); //session starts
$con=mysql_connect('localhost','root','');// connecting to ..........
mysql_select_db('news_db'); //connectin to db
if(isset($_POST['login'])) //if button login is pressed
{
$name=$_REQUEST['username'];//getting name
$password=$_REQUEST['password']; //getting password
$qyer=mysql_query("select * from news_tb where username='$name' and password='$password'"); //selecting fields
$row=mysql_fetch_array($qyer); //fetching values in row
if($row['username']==$name && $row['password']==$password)// condition to match the fields with database
{
header("location:news1.php"); // on else also this page is opening
}
else
{
echo "pls enter valid information"; //redirects to if condition and doesnt print the msg
}
}
Its because by pressing send or whatever, you post the code to the script. All you are doing is checking if it has been posted, not if the variables themselves are empty. Then if you have an empty row in mySQL, you will never use the else.