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.
Related
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");
?>
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 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.
So I'm really really really new to PHP and MySQL (just started today!).
I have a page that updates a MySQL database based on results from a post.
The way I have it now, the PHP code is on the page, and it works, but the problem is that it goes through on page load as well, that is, before the POST happens.
Any way to prevent this?
Here's my code:
<?php
//do stuff
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_row($result);
while($row = mysql_fetch_row($result)) {
//do something
}
}
else {
//do something else
}
// free result set memory
mysql_free_result($result);
$first = 0;
?>
<br />
<br />
<div id="addName">
<h3 class="caps">Want to add yourself?</h3>
<div class="box">
<br /> <br />
<form id="form1" name="form1" method="post" action="#">
Email:
<label>
<input type="text" name="email" id="email" />
</label>
<label>
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</form>
</div>
</div>
</div>
See, problem is that it will run //do something else before the form is filled out. Any suggestions?
Thanks!
Better Condition
if(isset($_POST['submit']) && !empty($_POST) ){
// now do with your post data
}
this will prevent empty data to be posted
if(isset($_POST['submit'])){
// do things when post has been made
// e.g. insert the data into SQL
}
Take a read of this page. The above code will check to make sure the submit button has been pressed.
If you are hosting the HTML form on a different page you can put this at the top of your code on the PHP page. It will redirect the user to the HTML form file before any code is executed.
if (!$_POST['submit']) {
header("Location: ./form.html");
die();
}
However if you prefer to keep the form on the same page (which it looks like you are) you can use the suggestions above.
Following on from a previous question, (previous question here), the problem I'm having seems to involve trying to pass/post a value through a form when the form action is '#'. I've tried session data but it always returns the last item from the database. Everthing else returns nothing.
Any help/ideas/advice greatly received, S. (Code below)
This is the code that displays the list of items, each containing an 'email' link/button to one instance of a popup window/form that is located at the bottom of the page.
<?php
$query = mysql_query("select * from istable where categoryID = '1'");
while ($result = mysql_fetch_array($query)) {
echo '<h4>'.$result['title'].'</h4>
<p>'.substr($result['descrip'],0,408).'... <strong>Read more</strong></p>
<form action="#" method="post" rel="#sheet" class="see">
<input type="hidden" name="propTitle" value="'.$propResult['title'].'">
<input type="submit" name="submit" value="Email">
</form>
';
}
?>
This is the code for the popup window/form at the bottom of the same page that is called through jquery.
<div id="sheet" class="rounded">
<!--{{{ pane1 -->
<div class="pane" id="pane1">
<h4>Email Details to a Friend</h4>
<p>You have selected to forward the details of <?php echo $_POST['propTitle']; ?> to a friend.</p>
<p>Please fill out the following form</p>
<form class="rounded" id="email-form" method="post" action="<?php echo $pageLink; ?>">
<!-- form goes in here -->
</form>
</div>
<!--}}}-->
</div>
<script type="text/javascript">
$(".see").overlay({mask: '#999', fixed: false}).bind("onBeforeClose", function(e) {
$(".error").hide();
});
</script>
Why are you using PHP for this? If the popup is called through the same page, use JavaScript to get the DOM element value and if you need to process data use AJAX.