I have a code like this
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
} else {
echo "wrong";
}
?>
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
I want to save values into db after user clicks the submit button. I have been trying different approaches, but still could not get near to it.
Any ideas/hints what I should do next or doing wrong?
After the given suggesstion below is my code :
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
<?php
if(isset($_REQUEST['submit1']))
{
echo "$thismemberinfo[msurf]";
echo " $msurfclicks";
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
//$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo " not set " ;
}
}
?>
you can use isset for checking if button is clicked or not
if(isset($_REQUEST['submit1']))
{
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
header("location:".$_SERVER['PHP_SELF']);
}
You need to check if the request has come from the post submit i.e. as others pointed check $_POST['submit']
if(isset( $_POST['submit'] ) {
// your complete rest php code goes here to insert the record
}
On page refresh, it'll see the request is not a post request submitted hence won't execute the php code in the if and will just display the page.
Your code is missing a few things..
To insert entries into the database, you should think more about what tasks need to be carried out, I'll give you a list of them, you have probably done some of these.
1) Connect to the database.
2) Obtain the values entered into the form, and store them in local variables, in your case you have used POST on your form and therefore.. here's an example:
$Field1 = mysql_real_escape_string($_POST['match']); // match?? This post data comes from the name field of your form.
3) Create your query... e.g..
$sql = "INSERT INTO table_name (table_heading) VALUES ('$Field1')";
4) Run the query
Related
I'm new to PHP, and I'm sure this is a common think to do, but 99% of the answers I have found to this involve AJAX, JQuery and/or JavaScript.
I am only allowed to use HTML/CSS and PHP in my project, so I need a working option that does not involve anything else.
I have the following setup:
index.php, this holds my form structure
insert.php, this sanitizes/validates and inserts form data into a database table
Leaving action as insert.php sends me to my insert.php page, which I want to keep private and for developer eyes only...no good.
form action=" " method="post"
// OR
form action="index.php" method="post">
Leaving action blank or as index.php keeps me on the same page, but...
I want to keep my form processing in a separate file (insert.php) and NOT on the same page, if at all possible.
Do I have any options for this that are not excessively complex in pure PHP?
Thanks for any advice.
(PS. If there's any blatant errors or poor form here, I'm all ears to constructive criticism)
Here's a snapshot of my insert.php file if its helpful. I can upload my form as well, but its very basic (just select a course, input first/last name, input student id).
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
Something like this might be what you want:
<?php
if (!empty($_POST)) {
require "insert.php";
}
?>
<html><head></head><body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
</body></html>
It's possible to submit the page to itself and check if the $_POST is empty or not. If it's empty show the form of the page if not insert the data into the database.
<?php if (!empty($_POST)):
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
<?php endif; ?>
I have displayed the data in a form edit.php and again paas the truk_id in url on update page to update.php the data of the fields but it's not working. Can anyone check this
PHP Code
<?php
$truck_id=$_GET['truck_id'];
print_r($truck_id);
include("assets/database_con.php");
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
$truck_number= mysql_real_escape_string(htmlspecialchars($_POST['truck_number']));
$truck_model= mysql_real_escape_string(htmlspecialchars($_POST['truck_model']));
$truck_make= mysql_real_escape_string(htmlspecialchars($_POST['truck_make']));
$truck_type= mysql_real_escape_string(htmlspecialchars($_POST['truck_type']));
$truck_tierweight= mysql_real_escape_string(htmlspecialchars($_POST['truck_tierweight']));
$truck_gvm= mysql_real_escape_string(htmlspecialchars($_POST['truck_gvm']));
$truck_regodate= mysql_real_escape_string(htmlspecialchars($_POST['truck_regodate']));
$truck_inspectaiondate= mysql_real_escape_string(htmlspecialchars($_POST['truck_inspectaiondate']));
$sql1 ="UPDATE add_truck SET truck_number='$truck_number', truck_model='$truck_model', truck_make='$truck_make', truck_type='$truck_type', truck_tierweight='$truck_tierweight', truck_gvm='$truck_gvm', truck_regodate='$truck_regodate', truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
echo $sql1;
$results=$conn->query($sql);
if($results)
{
print 'Success! record updated';
}else{
print 'no! record updated';
}
}
?>
You are assigning values to fields in single quotes.
The main string is enclosed within single quotes.
Variables inside single quotes are not parsed (value is not calculated).
This is called variable interpolation.
Use double quotes for whole string and single quotes for values.
Corrected SQL:
$sql = "UPDATE add_truck
SET truck_number='$truck_number', truck_model='$truck_model',
truck_make='$truck_make', truck_type='$truck_type',
truck_tierweight='$truck_tierweight',
truck_gvm='$truck_gvm', truck_regodate='$truck_regodate',
truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
you are using GET for the truck id and POST for all other variables - is this intentional?
$truck_id=$_GET['truck_id'];
should it be
$truck_id=$_POST['truck_id'];
or should all the other variables be from the GET array?
$truck_id=$_GET['truck_id'];
Here is your problem part you can't get values from get method when you submit. So you need to add some hidden field into your form like this
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
Change your code like this
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
}
I changed your code please look at this
//Your code starts now
<?php
include("header.php");
include("assets/database_con.php");
$truck_id= $_GET['truck_id'];
//print ($truck_id);
?>
<?php
//submit part in top that is better
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
$truck_number= mysql_real_escape_string(htmlspecialchars($_POST['truck_number']));
$truck_model= mysql_real_escape_string(htmlspecialchars($_POST['truck_model']));
$truck_make= mysql_real_escape_string(htmlspecialchars($_POST['truck_make']));
$truck_type= mysql_real_escape_string(htmlspecialchars($_POST['truck_type']));
$truck_tierweight= mysql_real_escape_string(htmlspecialchars($_POST['truck_tierweight']));
$truck_gvm= mysql_real_escape_string(htmlspecialchars($_POST['truck_gvm']));
$truck_regodate= mysql_real_escape_string(htmlspecialchars($_POST['truck_regodate']));
$truck_inspectaiondate= mysql_real_escape_string(htmlspecialchars($_POST['truck_inspectaiondate']));
$sql1 ="UPDATE add_truck SET truck_number='$truck_number', truck_model='$truck_model', truck_make='$truck_make', truck_type='$truck_type', truck_tierweight='$truck_tierweight', truck_gvm='$truck_gvm', truck_regodate='$truck_regodate', truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
echo $sql1;
die();
$results=$conn->query($sql);
if($results)
{
print 'Success! record updated';
}else{
print 'no! record updated';
}
}
?>
And changed some thing in here(added action="")
<form role="form" method="post" action="">
And changed some thing in here also(added name="submit")
<div class="form-group">
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
<input type="submit" value="submit" name="submit" class="btn_full" id="submit-booking">
</div>
No need for another div for hidden because it is 'hidden'
Used a new code as solution :
<?php
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
...
}
and one hidden value with the submit name of attribute :
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
<input type="submit" value="submit" name="submit" class="btn_full" id="submit-booking">
okay guys..
i have two pages
page1 contains a form
<form id="Form1" name="Form1" method="post" action="form1.php">
//form1.php is the page1 where this form is.. i have redirected to the
same page because this page contains the php validation code <input
type="text" class="input" name="txtName"
value="<?php if(isset($name)){echo $name;} ?>"
<?php if(isset($flag) && $flag == 1){echo "div style = 'border:2px solid red;'". "/div";}?>>
<input type="submit" name="submit" value="Submit" class="button3">
</form>
I send the data to page2 using php header-location method
php page1 code
if(NO ERRORS)) // in the form there is actual code
{
// insert into database
$result = mysql_query ( $insert );
if ($result) {
echo ("<br>Input data is succeed");
$lastInsertedId = mysql_insert_id ();
header ( 'Location:form1_conf.php?id=' . $lastInsertedId ); // form1_conf.php is the name of 2nd page
} else {
$message = "The data cannot be inserted.";
$message .= "<br />" . mysql_error ();
}
}
now comes page2
the page2 name is form1_conf.php & is used to display the form data to user so that he may check the form for error and if anything is wrong he can click on edit and go back to main form (page1) and re-enter the data and resubmit the form.
here is the page2 code
here i use php to receive the data from page1 as:
if (isset ( $_GET ['id'] )) {
$lastInsertedId = $_GET ['id'];
}
$query = "SELECT * FROM db_purchase_form WHERE id=$lastInsertedId";
$result = mysql_query ( $query );
while ( $row = mysql_fetch_row ( $result ) ) {
$name = $row [1];
}
and here is the html code to display this
<div id="DisplayForm">
<div class="dispText">
<?php echo $name; ?>
</div>
</div>
<a
href="form1.php?id=<?php echo $lastInsertedId; ?>&name=<?php echo $name; ?>"
class="button3">Edit</a>
Now when user cliks on this Edit button on page2 he is taken to page1.
Now i have two questions
when user clicks on edit and reaches back to page1, the field of name is vacant, while i already have used the php code to fill the data in that name field.
copied from above, form1 page1 code.
<input type="text" class="input" name="txtName" value="<?php if(isset($name)){echo $name;} ?>"<?php if(isset($flag) && $flag == 1){echo "div style = 'border:2px solid red;'". "/div";}?>>
how can i achieve this? that when user clicks on edit and reaches back to page1 then he can see the value he filled earlier in that form1 stays in the form field.
when the user is transferred to page2, after he submits the form, the url of page2 is somehting like this..
http://mydomainnane.com/site1/form1_conf.php?id=36
now the issue is this when i change the value from 36 to any number say 34 or 24, those values are pulled out from db which are on that location and is displayed. How can i prevent this unauthorized view of DB values by just changing the values in url?
Thanks a lot for all your help guys.
In form1.php define at the top:
if(isset($GET['name']) && $GET['name'] != ""){
$name = $GET['name'];
}
Here is HTML/JavaScript:
<form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>">
<input type="hidden" name="user" value="<?php echo $employee->id; ?>" />
<input type="hidden" name="auto" value="<?php echo $employee->stay_live; ?>" />
<h3><input type="checkbox" name="stay_live" onclick="document.forms.thisform<?php echo $employee->id; ?>.submit();" <?php if ($employee->stay_live == '1') { echo "checked"; } ?> title="Click to Stay Live Every Day" /> <?php echo $employee->name; ?>
</form>
Here is PHP:
<?php
if(isset($_POST['stay_live'])) {
$user=$_POST['user'];
$auto=$_POST['auto'];
if ($auto == 1) {
$sql = "UPDATE users SET stay_live = 0 WHERE id = '{$user}';";
}
if ($auto != 1) {
$sql = "UPDATE users SET stay_live = 1 WHERE id = '{$user}';";
}
mysqli_query($dbconnection, $sql);
}
?>
If you see the onclick code in the form, it will auto-submit form and do PHP POST. However, the onclick only works if the checkbox is NOT checked. If it IS checked, the screen does refresh, as if it did thing, but the POST is never submitted.
So to summarize; everything works as expected when the box is not checked and it needs to be set. But to UNSET it, the server function is never called. Can anyone see why?
note: this is test code, so please no comments on sql injection
Checkbox values are not sent when they are unchecked, so $_POST["stay_live"] is not set.
<?php
if (isset($_POST["user"])) // type="hidden" will be sent regardless of checkbox
{
if (isset($_POST["stay_alive"])) echo "Checkbox checked";
else echo "Checkbox not checked";
}
?>
Using Jquery I'd do the following: You need to make a file with the functions that you want to be executed. This file will receive via POST or GET
To your onclick attribute just add an if for your action variable, if(element checked) action = unchecked --- else action = check
--Jquery function
function cBoxSubmit($employId, $action){ // call it in your onclick attribute.
$.post("submitFunction.php",{action: $action, employId: $employId, ...},function(data){ // Parameters: URL file, variables which will receive, call back function
if(data){
// On Success or in your case if checked
// add some code if needed
}
else{
// If unchecked
// add some code if needed
}
}
}
NOTE: echo == return in your php file ... This is how you return data to the call back function in your Jquery function
I have Two forms in my index.php and am trying to get them to submit and POST their data seperatly
Form 1
echo '<form action="process.php?type=news" method="post">';
echo '<table cellspacing="0"><tr><th>';
echo 'Add News to News Feed';
echo '</th></tr><tr><td>';
echo 'Title:<br /><input name="newstitle" type="text" id="add" style="height:16px;width:525px;" size="80" maxlength="186" /><br />';
echo 'Main Body Text:<br /><textarea name="newsfeed" id="add" style="width:525px;height:78px;" maxlength="2000" ></textarea>';
echo '<input style="float:right;margin-top:5px;" id="button" type="submit" value="Submit" />';
echo '</td></tr></table></from>';
And Form 2
echo '<form action="process.php?type=suggest" method="post">';
echo '<table cellspacing="0"><tr><th>';
echo 'Suggest Additions to the Intranet';
echo '</th></tr><tr><td>';
echo '<textarea name="suggest" id="add" style="width:330px;height:60px;" maxlength="800" ></textarea>';
echo '<input style="float:right;margin-top:5px;" id="button" type="submit" value="Submit" />';
echo '</td></tr></table></from>';
I want these both to post and do the action after pressing the submit button, but currently the second form submit to the first forms action
How can i fix this???
EDIT: Also i am using .PHP for both the index and process page then using it to echo the forms onto the page
Also here is the process.php data
$type=$_REQUEST['type'];
$suggest=$_POST['suggest'];
$newstitle=$_POST['newstitle'];
$news=mysql_real_escape_string($_POST['newsfeed']);
if ($type == "news")
{
$sql=mysql_query("SELECT * FROM newsfeed WHERE title = ('$newstitle')");
$number_of_rows = mysql_num_rows($sql);
if ($number_of_rows > 0)
{
echo 'This Title is Already Taken';
}
else
{
$sql="INSERT INTO newsfeed (title, news) VALUES ('$newstitle','$news')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header('Location: index.php');
exit;
}
}
elseif ($type == "suggest")
{
$sql="INSERT INTO suggestions VALUES ('$suggest')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header('Location: index.php');
exit;
}
Could it be that you are not closing the form with </form>, but with </from>, so the code of the second form is in fact still inside the first form since the tags are never closed?
try giving the submit an on click for each form so in its submit buttons html put this:
onclick="document.forms["myform1"].submit();"
and for form 2 put
onclick="document.forms["myform2"].submit();"
Im not sure exactly what you would like to achieve, so heres my assumptions,
1. your form submits wrongly, eg, second form submits the first form's data
or
2. you would like to do both submits 1 after another.
FOR 1:
Do this.
<form id="form1" action="process.php" method="POST">
<input type="hidden" name="type" value="news">
....
</form>
Note the spelling
/form not /from
<form id="form2" action="process.php" method="POST">
<input type="hidden" name="type" value="suggest">
....
</form>
Note the spelling
/form not /from
Some pointers:
Instead of echoing out so many times, echoing out once is suffice! Remember echos slow down your script. Also I would not pass the type as a $_GET, post is always safer for forms, you can use a hidden field to add the type:
<?php
echo '
<form action="process.php" method="post">
<input type="hidden" name="type" value="news">
...
...
</form>';//Not </from>
?>
Then with the PHP part use a switch case instead of if elses, it will be easier to add features then splitting with another ifelse, plus the default block can be used for anything that dont match like the last else in an if else statement.
<?php
$type = $_POST['type'];
switch($type){
case "news":
...
break;
case "suggest":
...
break;
default:
//default if different type or no type is set
break;
}
?>
Also move over to PDO or prepared mysqli_ functions for your mySQL stuff its safer.