What I want to do is when the user clicks submit, the data gets entered to the database and it will redirect me to like a Thank you page showing what the user has submitted.
code snippet: html code & php code:
<form action="ThankYouReport.html" method="post"
enctype="multipart/form-data">
<div>
<div class="container">
<label><input
type="checkbox" name="check[]" value="Beans">Beans</label>
<label><input type="checkbox" name="check[]" value="Apple" >
Apple</label>
</div>
</form>
<?php
require('config.php');
if(isset($_POST['sub']))
{
$checkbox1=$_POST['check'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1.",";
}
mysql_query("INSERT INTO `list` (`checked1`) VALUES ( ','$chk')") or
die(mysql_error());
}
?>
I looked around and saw that you had to change the form action, I did that but for some reason my data won't get entered in my database.
How would I go about displaying the data to another page.
I know there been many post on this site but none of them help me.
Try this and see the comments within:
<?php
session_start(); // always do this at the very top of your script
require('config.php');
if (isset($_POST['sub'])) {
$chk = implode(',',$_POST['check']); // shorter than using foreach
$sql = "INSERT INTO `list` (`checked1`) VALUES ('{$chk}')"; // just a way of storing a query to a variable
if(mysql_query($sql)) {
$_SESSION['success_msg'] = 'Successfully added items '.$chk; // store a message or whatever into a session variable
// FYI if you wrap a string with single quotes, you cannot use a variable within like in above query string, but have to be concatenated using a dot (.)
header('Location: http://www.example.com/ThankYouReport.html'); // redirect on success
} else {
die('Could not insert query'); // or print this message
}
}
?>
<form method="post" enctype="multipart/form-data"><!-- remove action attribute or use name of script this is in. -->
<div class="container">
<label><input type="checkbox" name="check[]" value="Beans"> Beans</label>
<label><input type="checkbox" name="check[]" value="Apple"> Apple</label>
</div>
</form>
EDIT (based on the comment)
If you want to transfer data from one script to another, especially for something simple as a thank you page or similar you can use php sessions. You need to turn your thank you page into a PHP script like so:
thanks.php
<?php
session_start();
?>
<div>
<?php echo $_SESSION['success_msg'];?>
</div>
Related
i'm brazilian i does a website simple to sent a simple users data, but to do a test i want sent manually newer data in a link without need complete manual form if it run then i can use directly by my app to save all users data.
see my idea:
mywebsite.com/savedata?method=post&usernamesave=Nome&Misael&userxp=34&userid=35&userlevel=31&usermail=crod%40gmail.com&userprog1=1&userprog2=2&userprog3=23&userprog4=25&userprog5=25&userprog6=25&userprog7=100&userprog8=100&proceed=
if i can change this data from my app and using hrefs i can do this and save a simple data without a complex data connection, it's possible ?
<a href="mywebsite.com/simplepost?method=post&joao&6y"> << type of exeple.
But when i use this and press enterkey the data isn't saved into a textfile, why ?
i using this in php :
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_POST['usernamesave'];
$userxp = $_POST['userxp'];
$userid = $_POST['userid'];
}
If i got you right you want to save data using a post method. If this is what you want to accomplish, then you don't have to pass the variables in URL. This is the main difference between POST and GET method.
Now for data saving, i will assume that you all ready created a database and a table to save your information on it, so let's jump to the form and how to handle them.
<?php
/*
* First form one will be the POST method.
*/
if(isset($_POST)){
echo "post method where used from a form to send this variables";
var_dump($_POST);
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
When you click on submit the information will be sent and can be handled after.
In get method it's different you will see the variables inside the URL after hitting submit, and the same way you can send data to other pages.
<?php
/*
* Second form one will be the GET method
* Check the url.
*/
if(isset($_GET)){
echo "get method where made from a form with this variables";
var_dump($_GET);
}
?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username: </label>
<input type="text" name= "username">
<label for="age">Age: </label>
<input type="number" name="age"/>
<input type="submit" value="Submit">
</form>
Now in the url you should see something like
example.com/index.php?username=WaredNsour&age=24
I believe you are using the GET method to send information but in your PHP code, you are using the POST method to fetch them.
Try this :
if ($_SERVER["REQUEST_METHOD"] == "GET") {
/*Php 5.6.2 Code By : Michael S. author*/
//globais
$username = $_GET['usernamesave'];
$userxp = $_GET['userxp'];
$userid = $_GET['userid'];
}
In the code of your page that is processing the variables being sent, try the following (temporarily) as a test to see if variables are being sent/seen. If they are, they will be printed out.
<p>Post vars:
<?php var_dump($_POST) ?>
</p>
If nothing displays, try:
<p>Request vars:
<?php var_dump($_REQUEST) ?>
</p>
Note: in the url you posted you have: &Misael& if Misael is part of the username you should not use the & in front of it. http sees &s as separators for the variables. It will see Misael as a variable name, like: ...&Misael=something&.... If it is a space, use %20.
I am trying to redirect a to a new php page after the user has clicked on the submit button. I have got it to successfully send the form information to the MySQL database but then I cannot get a successful redirect.
I then changed some code and got it to successfully redirect but not send the form information to the database. My other php file is named nextForm.php and I have tried replacing the action="$_SERVER[PHP_SELF]" with the path to the nextForm.php file and I have tried using a require nextForm.php; line in the code where I want to redirect.
Here is the code I have currently:
<?php
//establish a connection to the MySQL db or terminate if ther is an error
$conn = mysqli_connect("localhost","root","mysql","covid_tech",3306) or die(mysqli_connect_error());
//HTML form to prompt user input
print <<<_HTML_
<FORM style="text-align:center" method="POST" action="$_SERVER[PHP_SELF]">
<div class="Customer_Name">
Enter Customer Name: <input type="text" name="Customer_Name" class="textbox">
</div>
<br/>
<div class="Contact_Name">
Enter Contact Name: <input type="text" name="Contact_Name" class="textbox">
</div>
<br/>
<div class="Contact_Phone">
Enter Contact Phone Number: <input type="text" name="Contact_Number" class="textbox">
<br/>
</div>
<button class="btn btn-1" style="text-align:center" onclick='disappear(this)' name="name_submit" method="POST" type="submit" value="find_cusName"><span>Enter Customer Name</span></button>
</FORM>
_HTML_;
//check to make sure the POST request was sent and check to make sure that there is a vlaue in the System POST variable
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['Customer_Name'])){
//SQL string to find the name that was input on the page
$find_name_sql = "SELECT cusName,cusID from customer where cusName = '$_POST[Customer_Name]'";
//run the query on the db
$result_find_name = mysqli_query($conn, $find_name_sql);
//Check to see if the query returned any rows
if(mysqli_num_rows($result_find_name) > 0){
//If it did, it should only be 1 row and we fetch it
$row = mysqli_fetch_row($result_find_name);
//set our current_id variable to the value in $row[1] which is the cusID attribute from the db
$current_id = $row[1];
}
else{
//sql statment to insert a new customer into the customer table of the db
$insert_first_customer = "INSERT INTO customer (cusName,contactName,contactNo) values('$_POST[Customer_Name]','$_POST[Contact_Name]','$_POST[Contact_Number]')";
//run the insert query
$add = mysqli_query($conn,$insert_first_customer);
}
//redirect to next form page here
}
mysqli_close($conn);
?>
The action attribute simply works as a way to direct your GET/POST requests. If you would like to redirect after running your PHP code, you should use the header() function or use a meta tag.
Example:
header('Location:'.$_SERVER['SERVER_NAME'].'/nextForm.php');
or
echo '<meta http-equiv="refresh" content="0;url=nextForm.php">';
and finish your code with the exit() function so an attacker could not bypass your redirect.
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 used a sample I found here with a HTML page calling a PHP script, both are listed below.
It all works well - BUT, I end up with the PHP scrip page and I want to avoid it - I want to stay on the HTML page and NOT move anywhere. I read in some places that I will need JS or AJAX but can't see any actual example.
I am working on my PC under Windows 7 with IIS version 7.5 installed, PHP 5.3.28.
and executing the HTML file inside c:\inetpub.wwwroot
HTML
<div id="contact">
<h2>Enter your First and Last Name</h2>
<form action="frm_script.php" method="post" target="_parent">
<p><strong>First Name:</strong><br /> <input type="text" name="firstName" /></p>
<p><strong>Last Name:</strong><br /> <input type="text" name="lastName"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</div>
PHP Script
<?php
if(isset($_POST['submit']))
{
//get the name and comment entered by user
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//connect to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'mdpdata') or die('Error connecting to
MySQL server');
$check=mysqli_query($dbc,"select * from clients where firstname='$firstname' and
lastname='$lastname'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0)
{
print "customer exists";
}
else
{
//insert results from the form input
$query = "INSERT INTO clients(firstName, lastName) VALUES('$firstName', '$lastName')";
$result = mysqli_query($dbc, $query) or die("Sorry, Duplicate Record.'$php_errormsg'");
mysqli_close($dbc);
}
print '<script type="text/javascript">';
print 'alert("The Customer is NOW registered")';
print '</script>';
};
?>
A html document containing a form with an action="" statement results to change to the assigned page. Like yours, to frm_script.php
If you don´t want this to occure, you need an AJAX-request, as you mentioned above, or you can add a
header(location: 'FPRM.HTML');
to the bottom of the php script. So after processing, which should be very fast, the original page is loaded again.
Or you don´t use two pages at all. Just put the html code from FPRM.HTML to the bottom, after the php code, so the page just will be reloaded once the form values are saved. In this case, call the concatenated document simply FPRM.php, and the form action must be set to action="FPRM.php" or is simply not needed, as the form without action statement loads the same page anyway.
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.