I have a small problem. I want to have a button in my html page that saves every data that is added in the textfields and also when I click it to move to the next page.
My code is the follow...
<input type=button onClick="location.href='education.php'" value='Next'>
but it only moves to next page it does not save the data in the database ...
Can you help me please?
Thanks.
Remove the JavaScript
Change the type to submit
Wrap it in a <form>
Set the action of the form to education.php
Set the method of the form to post
Then, in education.php, read the data from $_POST and use PDO (with bound variables) to insert it into the database.
Try this :
<?php
if(isset($_POST['submit']))
{
// Insert Query Put here
header('Location: education.php');
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="Next" name="submit">
</form>
</body>
</html>
education.php :
<?php
echo "Successfully Updated.";
?>
You will have to set an action to your form like below because you are not submitting the form, but just redirection to another page without taking the form data.
<form action="education.php" method="post">
<!-- All your input fields here -->
<input type="submit" name="submit" value="Next">
</form>
and your education.php should be look like this:
<?php
//Get all parameters using $_POST
//Make A connection to database
//Choose a database in which you have to save the data
//Create a SQL query
// run query using mysql_query($query);
//Redirect to anywhere with header("Location:page.php");
?>
Related
I am having trouble understanding handling variables that are passed through pages when a form submit button is clicked. Basically i have a text area where a user writes an sql query. Then clicks submit. Then on the same page (x.php) , i have to display the results in a table. I figured, when the user clicks the button, i call a function that connects to the database, then runs the query, and outputs the result in a table. The code i have below is a mock, and isnt quite working.But above is essentially what i am trying to do.
In my code, I call the page, and check to see if the proper submit button has been clicked, is that how i am suppose to do it?
Also, I am trying to post the metadata in the code below, but how does the table replace what is already on the page?
<html>
<head>
<title>CNT 4714 - Project Five Database Client</title>
</head>
<body style="background-color:white">
<center>
<h1 style="color:red">CNT 4714 - Project Five Database Client</h1>
<hr>
<div style="float:left; text-align:left;padding-right:80px; padding-left:80px; ">
<font color="yellow">
<?php
?>
Welcome Back!<br>
<?php echo $_POST["user"];?>
</font>
</div>
<font color="yellow">
<div style="float:left; text-align:left">
<center>
<h2 style="color:green">Enter Query</h2><br><br>
Please enter a valid SQL Query or update statement. You may also just press<br>
"Submit Query" to run a defualt query against the database!
<form action="" id="sql" method="post">
<br>
<textarea rows="10" cols="50" name="query" form="sql">Enter text here...</textarea><br><br>
<input type="submit" name="submit" color="red">
<input type="submit" name="" color="red" value="Submit Update">
</form>
<?php
if(isset($_POST['submit'])){
echo "hello";
query(); //here goes the function call
}
function query()
{
echo "hello";
$conn = mysqli_connect("localhost:3306", "root", "*******", "project4");
$query = $_POST["query"];
$result = mysqli_query($conn, $query);
$metadata = mysqli_fetch_fields($result);
print("<tr>");
for($i=0; $i<count($metadata);$i++){
print("<tr");
printf("%s",$metadata[$i]->name);
print("</tr>");
}
}
?>
</center>
</div>
</font>
</center>
</body>
</html>
You are trying to get the values of the global variable $_POST while you are posing it to $_GET. The way to fix this is assigning the method into your form element.
Example:
<form id="sql" action="" method="POST">
There are many ways for checking or the form is submitted, one of this ways (the one I am always using) is checking or the $_SERVER['REQUEST_METHOD'] is equal to "POST". This way you can tell the different between a GET, POST, or PUT request.
Example:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['sql']))
{
....
}
}
If you're using $_POST, your form request method should be POST.
<form action="" id="sql" method="post">
Otherwise, it will submit it with a GET request by default.
In that case, you will have to access the variable using $_GET instead.
I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
I want to store the text value submitted by clicking the submit button of a form, in a variable, so that I can use that variable for further querying the DB.
My Code:
<?
if($submit)
{
mysql_connect("localhost:3036","root","root");//database connection
mysql_select_db("sync");
$order = "INSERT INTO country (id,country) VALUES ('44','$submit')";
$result = mysql_query($order);
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
}
}
?>
<html>
<title>form sumit</title>
<body>
<form method="post" action="">
<input type="text" name="id" value="<?=$submit;?>"/>
<input type="Submit" name="submit" value="Submit">
</form>
</body>
</html>
//In real case, the form has elements with radio button containing values from a DB QUERY,
I wanted to use the selected item from the form to process another DB query in the same page...
Thanks in Advance
Try this -
<?php
$submit = $_POST['id'];
if($submit)
{
//your code is here
echo $submit;
}
?>
<html>
<title>form sumit</title>
<body>
<form method="post" action="">
<input type="text" name="id" value="<?php echo $submit; ?>"/>
<input type="Submit" name="submit" value="Submit">
</form>
</body>
</html>
Submitted form data automatically gets allocated to a variable ($_POST, in your case). If you want longer-term storage, consider using the $_SESSION variable, otherwise the submitted data is discarded upon script termination.
Please clarify your question, as I'm not quite sure what you are trying to achieve here.
In a normal workflow, you would first check if your form has already been processed (see if $_POST has any data worth processing), then query the database for whatever data you need for your form, then render the actual form.
As promised, here's a hands-on sample:
<?php
if ($_POST['ajax']) {
// This is a very trivial way of detecting ajax, but we don't need anything more complex here.
$data = workYourSQLMagicHere(); //data should be filled with the new select's html code
print_r(json_encode($data));
die(); // Ajax done, stop here.
}
/* Your current form generation magic here. */
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
// This should probably go into a separate JS file.
$('#select1').change( function() {
var url = ''; //Here we're accessing the page which originates the script. If you have a separate script, use that url here. Local only, single-origin policy does not allow cross-domain calls.
var opts = { ajax: true };
$.post(url, opts, function(data) {
$('#select2').replaceWith( $.parseJSON(data) ); //Replace the second select box with return results
});
});
</script>
<select id="select1"><?=$stuff;?></select>
<select id="select2"><?=$more_stuff;?></select>
I want to make a form which takes information then uses that information on another page when it is submitted. However once it redirects, it loses all the information from the other page for example:
Page 1:
<?php
if(isset($_POST['submit']))
{$info=$_POST['info'];}
?>
<html>
<form action='page2.html' method='POST'>
<input name='info'>
<intput type='submit' name='submit'>
</form>
</html>
Page2:
<?php
echo $info;
?>
it doesn't know what the variable 'info' is on page 2.
Add:
if(isset($_POST['submit']))
{ echo $_POST['info'];}
and remove:
echo $info;
Now reasons:
When you submit a form it's redirected to a page written in action attribute of form tag and sends form data to it. So after submitting form you are on the page2 where you have access to posted data.
If you are posting to page2.html then your form data will be in the global $_POST variable. Try
print_r($_POST);
in your page2.html php
in page 2:
echo $_POST['info'];
I don't know why you have the variables $_POST in the first page. Also you should name the page2 page2.php unless you have configured it otherwise in your web server.
Page 1:
<html>
<form action='page2.html' method='POST'>
<input name='info'>
<intput type='submit' name='submit'>
</form>
</html>
Page 2:
echo $_POST['info'];
Or, to see everything that's passed between pages:
print_r($_POST);
I have a little problem. I want to reload my page after submitting a form.
<form method="post" action="">
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input type="submit" value=" Update " id="update_button" class="update_button"/>
</form>
only use
echo "<meta http-equiv='refresh' content='0'>";
right after insert query before }
example
if(isset($_POST['submit']))
{
SQL QUERY----
echo "<meta http-equiv='refresh' content='0'>";
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
on your full page, you could have this
<?php
// check if the form was submitted
if ($_POST['submit_button']) {
// this means the submit button was clicked, and the form has refreshed the page
// to access the content in text area, you would do this
$a = $_POST['update'];
// now $a contains the data from the textarea, so you can do whatever with it
// this will echo the data on the page
echo $a;
}
else {
// form not submitted, so show the form
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit" value=" Update " id="update_button" class="update_button"/> <!-- notice added name="" -->
</form>
<?php
} // end "else" loop
?>
If you want the form to be submitted on the same page then remove the action from the form attributes.
<form method="POST" name="myform">
<!-- Your HTML code Here -->
</form>
However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header
function page_redirect($location)
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
exit;
}
// I want the page to go to google.
// page_redirect("http://www.google.com")
LOL, I'm just wondering why no one had idea about the PHP header function:
header("Refresh: 0"); // here 0 is in seconds
I use this, so user is not prompt to resubmit data if he refresh the page.
See Refresh a page using PHP for more details
You can maybe use :
<form method="post" action=" " onSubmit="window.location.reload()">
<form method="post" action="">
<table>
<tr><td><input name="Submit" type="submit" value="refresh"></td></tr>
</table>
</form>
<?php
if(isset($_POST['Submit']))
{
header("Location: http://yourpagehere.com");
}
?>
action attribute in <form method="post" action="action="""> should be just action=""
You want a form that self submits? Then you just leave the "action" parameter blank.
like:
<form method="post" action="" />
If you want to process the form with this page, then make sure that you have some mechanism in the form or session data to test whether it was properly submitted and to ensure you're not trying to process the empty form.
You might want another mechanism to decide if the form was filled out and submitted but is invalid. I usually use a hidden input field that matches a session variable to decide whether the user has clicked submit or just loaded the page for the first time. By giving a unique value each time and setting the session data to the same value, you can also avoid duplicate submissions if the user clicks submit twice.
//insert this php code, at the end after your closing html tag.
<?php
//setting connection to database
$con = mysqli_connect("localhost","your-username","your-
passowrd","your-dbname");
if(isset($_POST['submit_button'])){
$txt_area = $_POST['update'];
$Our_query= "INSERT INTO your-table-name (field1name, field2name)
VALUES ('abc','def')"; // values should match data
// type to field names
$insert_query = mysqli_query($con, $Our_query);
if($insert_query){
echo "<script>window.open('form.php','_self') </script>";
// supposing form.php is where you have created this form
}
} //if statement close
?>
Hope this helps.