save multiple form in one button only - php

I want to create a project that save the fill up forms in previous form and insert into database using one button only. For example answer1.php and answer2.php the save button is in the answer2.php i want to fetch data from answer1.php and save to databse same as in answer2.php
this code below insert data in one form only
$query = mysql_query("INSERT into holiday (holiday_no,holiday_name, status,campaign_name,holiday_type, createdBy, holiday_date, createdDate)
VALUES('$holiday_no', '$id','$status','$campaign_name','$hol', 'System','$date','$createdDate')") or die(mysql_error());
echo "Data has been saved with holiday name";

Not quite sure what you're asking for ...but giving it a try ;-) :
You can put the key-value pairs the first script receives into the next form so they get transmitted once again to the second script. E.g. if in the first step something like category=foo and country=bar gets transmitted write out a form that looks like
<form method="POST" action="answer2.php">
<p>
<input type="hidden" name="category" value="foo" />
<input type="text" readonly="readonly" name="country" value="bar" />
<!-- all the other things you want to add to the form -->
<input type="submit" />
</p>
</form>
But keep in mind that a) you need to encode the values properly for html output, otherwise your scripts are vulnerable for injection attacks, see http://docs.php.net/htmlspecialchars
and b) your second script can't "be sure" that the values haven't been altered or even transmitted to the first script at all; if you need that (e.g. for some transaction mechanism) you need something else like e.g. http://docs.php.net/features.sessions

Use hidden fields, a session, or a temporary table.
<?php
if (empty($_REQUEST)) {
echo '<form action="', $_SERVER['PHP_SELF'], '">
</form>';
} elseif (empty($_REQUEST['some_field_from_your_second_form']) {
// Do the second part of your form
} else {
// Do the final submission
// Sanitize the values
// Insert in the database
}

Related

Process PHP form on hidden page, but stay on same page. No Ajax, pure php only (project)

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; ?>

Add data to $_POST and submit to another page

I'm trying to add a value to $_POST data while it gets submitted to the target page as follows:
post.php
<?php $_POST['field1'] = "Value1";?>
<html>
<head>
</head>
<body>
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
catch.php
<?php
foreach ($_POST as $key => $value) {
echo $key . " : ". $value;
echo "<br/>";
}
?>
but I cannot catch 'field1' on the other end. I don't want to use a hidden input field. How can I achieve that?
Thanks!
When you send the form, the $_POST data is reset and assumes only the inputs inside the form and a possible query string you may have appended to form action.
The best way to accomplish what you want is using hidden field but since you dont want it, you can append a query string to your form action:
<form method="post" action="catch.php?field1=Value1">
You're not submitting field1 anywhere. What happens is this:
post.php generates a HTML page (one that doesn't contain any reference to field1)
the user's browser renders the page
on submit, only the elements inside the form are submitted
catch.php receives the elements submitted above.
In other words, you need to get that value into your form:
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input name="field1" type="hidden" value="<?php echo htmlspecialchars($_POST['field1']) ?>"/>
<input type="submit" value="Submit" />
</form>
There is no other way to get the value into your POST data, if it's not present in the form. What you could do as a workaround is store the data in GET (size limit), session (concurrency issues - what happens when the user has two tabs open, each with different session data?), or cookies (size limit AND concurrency issues).
You can't do it this way. If you want to send the data you're trying to add to the POST there only through the users form, you are forced to also store it somewhere client side (e.g. a hidden field or a cookie). What you're doing right now is setting some value into the POST variable, but it gets overridden by the users form post (or rather the $_POST variable you're using after the form post is another instance).
What you could do instead to keep it serverside is save the value in the variable to the session of the user, then in the form post action server side get the value again (given the fact that you're using sessions). Lastly you could just store it in some table in a database, though I wouldn't do this.
Since $_POST are data sent by post method to script, you can not use it for another request directly. You need to compose and send another post request. The easiest way for you will be to use hidden input field/s.
Or you can choose another approach to make http post request, for example curl methods.
If you don't need data to be given by post method, you can save it in session, for example.
try this:
in post.php
<?php $_SESSION['field1'] = "Value1";?>
<html>
<head>
</head>
<body>
<form method="post" action="catch.php">
<input name="field2" type="text"/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
in catch.php
<?php
if(isset($_SESSION['field1']))
{
$_POST['field1'] = $_SESSION['field1'];
unset($_SESSION['field1']);
}
foreach ($_POST as $key => $value) {
echo $key . " : ". $value;
echo "<br/>";
}
?>
Make sure you have started the session.
Note: you must use hidden elements or query string as other user suggested.

Submit a form from another form, $_POST values

I have a value coming from another form in the same page called $_POST['serial']. And i want to use this value to run a query in another form but after I submit the second form nothing happened and the query not running.
<?php
if (isset($_POST['serial'])) {
$serial = $_POST['serial'];
?>
<form action="" method="post">
<button type="submit" name="submit">Click to use</button>
</form>
<?php
if (isset($_POST['submit'])) {
$query = mysql_query("UPDATE table_name SET status = 'inactive' WHERE serial = '$serial'");
}
}
?>
To pass the variable along you would create a hidden input on your second form to contain the value:
<?php
// check and clean up the passed variable
$serial = isset($_POST['serial']) ? htmlspecialchars($_POST['serial']) : '';
?>
<form action="" method="post">
<input type="hidden" name="serial" value="<?php echo $serial; ?>" />
<button type="submit" name="submit">Click to use</button>
</form>
For Safety's Sake
Your script is at risk for SQL Injection Attacks.
If you can, you should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really not hard.
Additional Thoughts
If you're planning to do a two-step form you'll likely want to place all of the data processing outside of the form page, in a separate PHP file. With the limited code that you have shown I fear that we will miss something in our answers which will lead you to additional questions because your code still isn't working as you would expect.
A button needs a name and a value to be successful. Your button doesn't have a value so $_POST['submit'] will be undefined.
Add a value attribute to your <button> element.
After you do that, $serial will be undefined because your form doesn't submit that.
You need to include it in your form too:
<input type="hidden" name="serial" value="<?php echo htmlspecialchars($serial); ?>">

PHP with input form with text - do a MySQL query when form focus changes

I am looking for some help about how to make input form handling in PHP.
What I need is when a user writes data into a text form (table1), and moves to another text form (like pressing TAB, or selecting with mouse), then it should start and MySQL query to see if such data written at table1 already existing in the matching MySQL table.
My goal is like to do it without pressing submit button. Something like when google checks if an username you want to register already exists.
I am thinking about something like this:
$duplicate_data_test ="";
if (focus has moved to another form field - how to check ?) {
$query = "SELECT table1 FROM testdatabase WHERE table1 = "' . (table1 from the form below - how to get data from the this form field without POST?) .'";
$result = mysqli_query($con,$query);
if(mysqli_num_rows($result)>0) {
$duplicate_data_test = "This data is already found in the database. Choose something else";
}
}
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="text" maxlength="30" name="table1">';
echo '<span class="duplicaterror">'. $duplicate_data_test.' </span>';
echo '<input type="text" maxlength="30" name="table2">';
echo '<input type="submit" value="OK">';
echo '</form>';
Thank you very much for your help!
You cannot do your "interface" check with php.
Your "focus has moved to another form field" has to be done with javascript.
First, Build your form with html like this
<form name="testForm" action="postForm.php" method="POST" id="myForm">
<label>INPUT 1 : </label>
<input type="text" id="in1" value="" name="input1" />
<label>INPUT 2 : </label>
<input type="text" id="in2" value="" name="input2" />
<div style="color:red;font-weight:bold;" id="error"></div>
<button id="submitButton">SUBMIT</button>
</form>
Then make your checks when user clicks on submit button with javascript/jquery & ajax (prevent event form posting) like this :
$(document).on('click','#submitButton',function(event){
event.preventDefault();
if($.trim($('#in1').val()) == ''){
//input 1 is empty
$("#error").html('INPUT ONE IS EMPTY');
}//....continue checks
Finally, if your checks are good, then post your form
$("#myForm").submit();
and if your checks are not good then display user a message!
$("#error").html("MESSAGE!");
I made you a little example on how to do it (it's not the best way to do it but it's just an example) on jsfiddle, check this link : http://jsfiddle.net/9ayo89jt/2/
hope it helps!
checking if something exists will need an AJAX call
put the query that checks the database in a separate php file and call it with AJAX
to submit once all input fields are filled, you will need to use javascript .. check if field 1,2,3,..etc. are not empty .. formName.submit()
this is a bad approach in my opinion

Best Way to Post Data from Large Forms & Hold Data in Inputs after Errors

This is a "best practice"/"most efficient" question. I have a large form (20+ fields). Form post into one large MySQL table.
No I can't break up the form and no, I can't break up the table (its being used to hold measurements); used by admin sales reps. Also, I don't want to use Javascript.
I know I can do this:
HTML
<form action="etc.php" method="post">
<input type="text" name="neck" value="">
<input type="text" name="arm" value="">
<input type="text" name="back" value="">
<input type="text" name="chest" value="">
<input type="text" name="legs" value="">
<submit button>
PHP
<?
$_POST['neck'];
$_POST['back'];
$_POST['arm'];
$_POST['chest'];
$_POST['legs'];
$postMeasurements = "INSERT INTO measurements (etc, etc, etc,) VALUES (etc, etc, etc) WHERE etc='etc'; query ($postMeasurements);
?>
But is there a faster way? Instead of having to declare each individual post, simply just run a loop that takes all the data post and inserts into the table. Even if the data has be in the same order of the columns of the table or if the input names have to be the same as the table column names is fine by me; I am just getting tired have to keep writing all these $_POST variables into.
Second question: What is the best way to hold this data in case of an error? As it stands now, I hold everything in $_SESSION (one session variable for each input), then redirect back to the form page if there is an error with an error message. then echo each $_SESSION variables as that inputs value.
Thanks,
if the fields as the exact names as the field names. post can only have the fields and nothing else
//if $_POST has the form then, also this is very unsafe because there is no injection prevention too
$sql = "INSERT INTO table (" . implode(",", array_keys($_POST)) . ")"
. "VALUES ('" . implode("','", array_values($_POST)) . "')";
You can directly use $_POST['foo'] inside your query, and need not declare :) .
holding the data could be in session, or inline cache, if you have huge data, its better to use some cache in server, and onload of the form, it retrieves the data from server based on SESSION_ID
Have the page post to itself.
Then do something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
// validate and insert post data
header("Location: $successUrl");
exit();
}
?>
<form action="etc.php" method="post">
<input type="text" name="neck" value="<?= $_POST["neck"]?>">
<input type="text" name="arm" value="<?= $_POST["arm"] ?>">
....

Categories