How can I get back (to the browser) some data automatically (from server) after a POST?
I have a HTML form
I POST the form's data to a php code eg: saveRecord()
the php code saves the data in a mySQL DB
if the data contains a non 0 record ID there will be an UPDATE, if the record ID == 0 there will be an INSERT, and the php code knows (gets back from DB) the new record ID
(after INSTER) how can I send that new record ID back to (browser) HTML form?
If I edit an existing record (ID !=0 ), everithing is fine...
My problem is that, when I post NEW data (ID == 0) I can post it several times, and the php code each time creates a new record in the DB... But I really don't want that. I would like to send (from the server) back (to the browser) the INSERTed records ID (right in the HTML form), to prevent multiple INSERTs...
How can I do that?!
the specific CI code:
function update($record) {
print_r($record);
$id = $record['crn_id'];
$record['crn_active'] = ( ($record['crn_active'] == 'on') ? 1 : 0 );
array_shift($record);
if ($id == 0) {
$this->db->insert('currencies', $record);
} else {
$this->db->where('crn_id', $id);
$this->db->update('currencies', $record);
}
}
?>
Here are three ways to help you on your way that can be generalized:
Make another column unique. If you care so much about possibly having duplicate data in your database there may be some rule to it that you can generalize in the form of a constraint.
Disable the submit button after it was clicked (e.g. <input type="submit" onsubmit="this.disabled=true">). (make sure to re-enable it if some ajax based validation fails)
Use a one time key generated to make sure the user did not just reload the submitted page. Have a look at form keys which can also help against CSRF and XSS attacks.
Related
This code is used to put a data in the database once the button is activated and then take it off and replace it by(Question save!). The problem is it take me two attempts to make it disappear(the button). $numofrow is used to verify if the action was once made(the action of the submit button). The problem is not the database,query,etc, its really the button. Thanks for your time.
This is my code:
if(isset( $real_domaine)){
$tt = "SELECT*FROM uniwix.table0 WHERE id= '$id' ";
$rr = mysqli_query($database,$tt);
while($rows = mysqli_fetch_assoc($rr)){
[rows call...]
$md = "SELECT*FROM uniwix.table1 WHERE usern='$us' and question='$sujet'";
$ao = mysqli_query($database,$md);
$numofrow = mysqli_num_rows($ao);
if($numofrow == 0){
echo '<form action="" method="POST">
<input type="submit" name="sauvegarder" value="Save the question"/>
</form>';
if(isset($_POST['sauvegarder'])){
$qu = "INSERT INTO database (usern,question) VALUES('".$us."','".$sujet."')";
$sm = mysqli_query($database,$qu);
}
}else{
echo 'Question saved!';
}
//end of while loop
}
// end of if(isset( $real_domaine))
}
The problem is not the database,query,etc, its really the button.
The button is almost passive, all it does is to send the data to the server when it is pressed. The error is in the (lack of) logic of the PHP code.
When the script runs for the first time, $numofrow is 0. It runs the echo that generates the form with the button then it checks if $_POST['sauvegarder'] is set. It is not set, of course, because when the page is loaded for the first time, the GET method is used.
The user presses the button, the data is submitted using POST and the code runs again. $numofrow is still 0 (no data was inserted in the database yet), the form is displayed again but this time $_POST['sauvegarder'] is set and the data received from the browser is saved into the database.
You need to rethink the logic of you page.
More, the form is empty. Maybe it works but this is not the correct way to write forms. The input fields you want to send to the server must stay in the form.
Even more, and the most important of all, your database code is a candidate for SQL injection. Don't build queries using string concatenation. Use prepared statements. Also read about how prevent SQL injection in PHP.
function appoint_del(sat,sat1)
{
if(confirm("Are You Sure To delete Selected Person Details Completely?"))
{
document.form1.action="student.php?cedit="+sat+"&did="+sat1;//
document.form1.submit();//an alternative to call form
}
}
<?
if($_GET['did']!="")
{
$del=executeupdate("delete from table2 where id=".$_GET[did]);
redirect("student.php?succ=3");
}
?>
To delete the content in data base by clint I have successfully did the job but I am not completelly aware of what is happining by the statement1 document.form1.action="student.php?cedit="+st+"&did="+st1;
and statement2
document.form1.submit()
can any one explane it?
and can sugest any good reference book for clarifing these type of doubts?
document.form1.action="student.php?cedit="+sat+"&did="+sat1;
This line of JavaScript sets a html form's action to the student.php page and appends the two parameters "cedit" and "did" along with their values. I assume you have a form on your page somewhere.
document.form1.submit();
This submits that form. I don't know where to or by what method (POST, GET) because you haven't provided any details on the form. I assume it submits back to the same page because the next line is a handler:
if($_GET['did']!="")
This detects whether the form was submitted by checking if the "did" parameter is present.
$del=executeupdate("delete from table2 where id=".$_GET[did]);
This seems to execute a database query with a massive SQL injection vulnerability. Very dangerous.
redirect("student.php?succ=3");
Redirects back to the same page again, this time passing in a different "succ" parameter which I assume is handled via some other code that you haven't provided.
Am fairly new to PHP and am making a basic CRUD style management system. I Have an update page and it displays data from a News table, and populates a form with it. The current picture ?(reference) is pulled through and displayed on the form. However if a user wants to change the picture they can press a 'delete' button and then I have written some PHP to display a upload button, set the values in the database for the image to null and hide the delete button, allowing the user to upload a new picture.
The Delete button only removes the reference (path) to the picture from the database, it doesn't delete the actual picture.
This is the HTML control to show the image and delete button. It also shows how the delete button works:
<td align="right">Image 1:</td>
<td align="left"><img src="uploads/newsimages/<?php echo $row["Image"]; ?>" width="230" border="0"> delete</td>
As you can see, when clicked it sets change=imagex and cid= the current news id.
There is then an if statement I have written, but it doesn't seem to only get activated when the delete button is clicked. Because I always get an error that 'cid' is undefined. It is as follows:
<?php
if (isset($_GET['change'] = "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I am pretty sure my lack of PHP knowledge is letting me down and I am trying to go about this the wrong way, because however I alter the if statement it always gives me an error. First it was cid is undefined so I changed to id but i already use that for something else, another query/function. I hope that all amde sense, can anyone tell me where Im going wrong?
You are missing a parenthesis + you have to specify individually:
if (isset($_GET['change'] = "image1") {
Change to:
if (isset($_GET['change']) && $_GET['change'] == "image1") {
Some more things to consider:
1) Don't use unsanitized values directly from $_GET in a mysql query
WHERE NewsID =".$_GET['cid']."
It is very easy to exploit this with some funky sql injection (see http://xkcd.com/327/ ).
If you are using numeric values for cid, you should cast your $_GET value to integer to prevent sql injection:
$cid = (int)$_GET['cid];
$query = '(...)WHERE NewsID = '.$cid.' limit 1';
Or even better:
$cid = (int)(array_key_exists('cid', $_GET) ? $_GET['cid'] : 0);
if ($cid) {
$query = (...)
}
If you need this kind of sanitizing in different places, you should think about writing a helper function for it to keep your code readable.
2) Don't use GET requests to change data on your server
Imagine a google bot browsing your site and following all those links that you use to delete images. Other scenarios involve users with prefetch plugins for their browsers (e.g. Fasterfox). Also, GET requests may be cached by proxies and browsers, so that the request won't hit the server if you click the link.
The HTTP specification comes with numerous request methods, the most important ones are:
GET to fetch content from the server
PUT to store new information on the server
POST to update existing information on the server
To update your news record (by removing the image) the appropriate method would be POST. To send a POST request, you can use the <form method="POST"> tag.
try this
<?php
if (isset($_GET['change']) && $_GET['change'] == "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I have a page with two forms on it (and two submit buttons), and the forms link the page back to itself with action="" for the INSERT INTO statements. One of the INSERT INTO statements is:
<?php
$sql="INSERT INTO panelProduct (length_mm, width_mm, aperture)
VALUES ('$_POST[p_length_mm]','$_POST[p_width_mm]','$_POST[p_aperture]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
One of the reasons I have put the form and the INSERT statements on the same page is that the form allows users to add products to an order, and there may be several products (so I thought the user could keep submitting until they're done...). The other reason was that I need to use a $_POST value sent from the previous page to do something else with the products they enter, and I don't know how to send it to more than one page.
Anyway, the problem I have found is that a new row is inserted into the database every time the page is refreshed, containing NULL values. This makes sense to me as the PHP will execute the statement above every time it encounters it. My question therefore is how I can make some sort of condition that will only execute the INSERT statement if the user enters something in the form and 'Submits'?
you could use the empty() method of PHP to check for null values in each of the variables.
Something like:
if(!empty($_POST['p_length_mm']) && !empty($_POST['p_width_mm']) && !empty($_POST['p_aperture']))
{
//execute your query here
}
else
{
//if there's an alternative you would like to happen if values are null, or just leave out.
}
Hope that does the trick.
You have to check if data come from your form. I'd suggest this approach - name your submit button (i.e. <input type="submit" name="my_submit_button" value="Whatever" /> and this condition to your insert code:
if( isset( $_POST['my_submit_button']) ) {
.. process your post data
}
Also, always remember not to trust user provided data. Verify if all data expected are present in$_POST and format matches requirements (i.e. you ask for number and received letters etc). If all test passed, then you are ready to commit your data to DB.
You need a condition like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// a form was posted
}
Of course, you still need to check whether your post actually contains the right stuff:
isset($_POST['p_length_mm'], $_POST['p_width_mm'], $_POST['p_aperture'])
Even better is to use filter_input_array() to sanitize your incoming data; your current code is open to SQL injection attacks. Using PDO or mysqli and prepared statements is the way to go.
wondering what the the best way to achieve something is.
To summarise, I have a form that I load by ajax which I use for to both update and insert new rows into a database. To determine whether it is an update or an insert I use the below code (updated forms use the mysql query to populate the form fields).
My code seems sloppy and not best practice. Are there any other suggestion on what would be the best way to do this?
<?
require_once("config.php");
$insert = false;
$update = false;
$targID = 0;
if(isset($_POST['targID'])){
$targID = $_POST['targID'];
$targRow = mysql_fetch_array(mysql_query("select * from events where eventid=$targID"));
$update = true;
}else{
$insert = true;
}
?>
<script type="text/javascript">
var insert = <? echo $insert; ?>+0;
var update = <? echo $update; ?>+0;
......javascript button events, validation etc based on inssert/update
</script>
You already know in the client whether it is an update or an insert, by the fact that you send or do not send the POST data item. So I would write JS in the original page to control the submit and what to do with the data that is sent back. It's difficult to write code without seeing the rest of the page, but at pseudo-code level, you could do the following:
use onsubmit() to catch original submit action
look to see if targID provided
if yes, send update request to server. When row data comes back, fill out form details and display form (you can 'show' a hidden DIV containing the form, for example)
if no - do you need to send anything? - just reveal an empty form (again, show a previously hidden DIV)
Hope this is useful in some way.
You should use native mySQL:
INSERT ... ON DUPLICATE KEY UPDATE
See:
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
What's the point in determining that on the client side? Does it make any difference?
For the server side I'd use $targID passed from the hidden field. if it's greater than zero - update, otherwise - insert.