Issue with mysql data storage into database [duplicate] - php

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.

Related

previously inserted value gets inserted automatically on page refresh

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.

no results in inserting values to MySQL with AJAX

on my research site, I have a few radio buttons and I want to send their values to MySQL table using jquery and AJAX. All buttons and jquery code are put in single-project.php (I modified WordPress theme) and the bits of code that should handle interaction with the MySQL are put in the db.php in the same folder.
However, something is not in order, because values do not appear on the database table. Could someone help?
jquery:
//the last button
$('#submit_last_button').click(function(){
SomeVariable = $('input:radio[name=lastRadio]:checked').val();
if (!$("input:radio[name=lastRadio]").is(":checked")) {
$("label#lastRadio_error").show();
$("input#lastRadio").focus();
return false;
} else {
if ('input:radio[name=lastRadio]:checked')
$('#PreviousButtonDiv').hide();
$('#NextDiv').show();
$.post('db.php',{action: "submit_last_button", previous_variable:SomePreviousVariable, last_variable:SomeVariable},function(res){
$('#result').html(res);
});
}
});
});
db.php:
<?php
$con = mysql_connect('localhost','user', 'password');
$db = mysql_select_db('my_database');
if($_POST['action'] == 'submit_last_button'){
$previous_variable = mysql_real_escape_string($_POST['previous_variable']);
$last_variable = mysql_real_escape_string($_POST['last_variable']);
$sql = "insert into MyTable (id, variable1, variable2) values ( NULL, '$previous_variable', '$last_variable')";
$query = mysql_query($sql);
if($query){
echo "Record Inserted.";
}else {
echo "Something Wrong!";
}
}
?>
There are various possibilities of what is not working on your code. But first, the problem is not in AJAX not saving on MySQL. AJAX is passing your data to the php script on your server to then, save it on MySQL.
Check if the values are reaching your script correctly;
Check if you're getting a db connection - check error logs or print them out;
Check if you're not getting a SQL syntax erro - again, check for logs;
Check if auto-commit is true (it is by default).

Continue the process after IF statement (regardless of the condition), php

I have searched a lot but can't find my solution. I am new to php so I hope I can explain my question clearly.
I am trying to build a system that allows the user to update his/her information.
There are some inputs in the form which are; username, email, old-new password...
What I want to achieve is updating only the changed inputs. (blank inputs will be ignored)
So I want the username input to be checked if it is blank and keep the process working regardless of the result if username is blank or not.
By that way ı can update the table with only changed/typed inputs.
How can I achieve that?
if($username != "") {
//update the username
}
// keep process going even if username condition is true.
if($email != "") {
// update the email
}
PS: I didn't write the whole codes because there are at least 10 inputs and 3 selects. I tried lots of nested if,elseif,else statements so the codes I tried is so complicated and long.
I just wonder If there is a way to keep the process going after an "if statement" even if the condition is true.
UPDATE
I tried using just ifs, I was expecting the process will be continue but, for example;if I left blank the username and type the email, it updates the email.But if username input was typed and the email was typed; it just updates the username.
What could be the problem ?
If all the data is updated on a single table say users, then you can generate the update command on the fly using the input data and finally execute the query as
<?php
$qry_update = "UPDATE `users` SET " ;
if($username != ""){
$qry_update .= "`username` = '$username', ";
}
if($email != ""){
$qry_update .= "`email` = '$email', ";
}
....
....
$qry_update = rtrim($qry_update, ',');
$qry = $qry_update." where idusers = $idusers ";
// Execute the query
?>
The above is conventional way of doing it. But its better to use PDO with bind params.
In PHP, the code outside your if statement will be executed.
The example you provided will check both if statements, and execute the code within if your statement is true.
So have you tried the following?
if (!empty($username)) {
// Do something to username
}
// Code here will still execute
So here the if statement will run if it is true otherwise it will just skip it.
elseif will have to go after an if and catches a next scenario, but if they need to be run all then don't use elseif
if ($condition) {
// code to run if statement passes
} elseif ($condition) {
// only checks the condition if the first if is not run
} else {
// has no condition but only runs if all above does fail to run
}
// Code here will still run as long as the above does not cancel the script. As Fatals, exit() die() return etc.

Php message updater clearing row instead of updating it

I am using the following script to process a form that updates a message on my website, the problem I am having is that it is clearing the row instead of updating it for some reason. I have copied the query from Phpmyadmin so I know its correct, and I have also tried echoing the posted values and they all echo out just fine too, but for some unknown reason when I click submit in the form it just wipes the contents of the record instead of updating it.
<?php
include("connectmysqli.php");
if (isset($_POST['OnOff'])) {$OnOff = $_POST['OnOff'];}else {$OnOff = '';}
if (isset($_POST['title'])) {$title = $_POST['title'];}else {$title = '';}
if (isset($_POST['message'])) {$message = $_POST['message'];}else {$message = '';}
$stmt = $db->prepare("UPDATE `itsnb_chronoforms_data_urgentform` SET `title` = '$title',`message` = '$message',`OnOff` = '$OnOff' WHERE `cf_id` =1;");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
echo 'Message Updated !';
echo '<p>Back To Main Menu</p>';
?>
This is the table :
did you echo the generated query?
there are exactly to ways I see this can happen:
your form input names do not match the post keys you check in the three if statements
you're not sending the form with method="post"
also you should only execute the update query if all three post fields are set and valid. like title and message must not be blank/empty and that onOff variable should eighter contain "on" or "off". otherwise echo an errormessage so the user knows what's wrong with his input.

Errors for changing variables content depending on session status [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Errors for changing variables content depending on session status
Hello! I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if(isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISPLAY, DEPENDING ON SESSION---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISPLAY, DEPENDING ON SESSION---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
From what I can see, there are no errors.
The id just doesn't match logoptions.
Most likely, you are changing the id or logoptions somewhere between tha assignment and the final check. Try a vardump in both locations on both variables to see if they still match.
Btw, you can use intval() or simply cast as (int) instead of the regex

Categories