I have been trying to get the PHP code to submit an email to a mysqlDB, but for some reason it is not working:
This is the form code in the HTML
<form class="header-signup" action="registration.php" method="post">
<input name="email" class="input-side" type="email" placeholder="Sign up now">
<input type="submit" value="Go" class="btn-side">
<p class="hs-disclaimer">No spam, ever. That's a pinky promise.</p>
</form>
For the PHP, I did the following (DB connection infos set to xxxxx):
<?php //start php tag
//include connect.php page for database connection
$hostname="xxxxxx";
$username="xxxxxx";
$password="xxxxxx";
$dbname="xxxxxx";
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
//Include('connect.php');
//if submit is not blanked i.e. it is clicked.
If(isset($_POST['submit'])!='')
{
If($_POST['email']=='')
{
Echo "please fill the empty field.";
}
Else
{
$sql="INSERT INTO MailingList (MAIL) VALUES('".$_POST['email']."')";
$res=mysql_query($sql);
If($res)
{
Echo "Record successfully inserted";
}
Else
{
Echo "There is some problem in inserting record";
}
}
}
?>
Do you know what might be the problem?
The php file is in the same folder than the webpage.
Thanks for your time
Regards
$_POST['submit']
does not exist, you have to specify the name for the submit button
<input type="submit" name="submit"........>
Please try this
You could also use this conditional for a POST request
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
And check the input with a var_dump($_POST); to see if the value exists in the array.
This is only if you're expecting one form. If you want multiple forms on the page you could make use of naming your submit button in the HTML code
<form class="header-signup" action="registration.php" method="post">
<input type="submit" name="action1" value="Go" class="btn-side">
</form>
You could also use this if you set an name on the submit button
if(isset($_POST['action1']))
{
var_dump("hit");
}
Related
I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.
This is the delete code which isn't working:
<?php
if (isset($_POST['deleteSubmit'])) {
$details = $conn->real_escape_string($_POST['deleteNum']);
$deleteSQL = "DELETE FROM userName WHERE id = '$details'";
$result = $conn->query($deleteSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>DELETE NAME (DELETE)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="num">Enter User Reference to be Deleted:</label><br>
<input num="deleteNum"type="number"><br>
<input num="deleteSubmit" type="submit" value="Delete">
</form>
For reference, this is the post code which is working (it's being used to add names to the database):
<?php
if (isset($_POST['nameSubmit'])) {
$details = $conn->real_escape_string($_POST['newName']);
$insertSQL = "INSERT INTO userName (name) VALUES ('$details')";
$result = $conn->query($insertSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>ENTER NAME (POST)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="fname">Enter Name:</label><br>
<input name="newName"type="text"><br>
<input name="nameSubmit" type="submit" value="Submit">
</form>
The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.
The database has one table called userName which contains two columns id (which is auto incremented) and name.
I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.
I see no error messages when enter an id and click the delete button.
For anyone who reads this in future, the query was solved by #kenlee;
(1) Change num="deleteSubmit" to name="deleteSubmit"
(2) change num="deleteNum" type="number" to name="deleteNum" type="number"
(3) Please use paratemerized prepared statement in your queries
Im having some Trouble getting a simple PHP Login form to pass and check Login Data against a Database. For some reason the Data will not pass across from the Html Form to the PHP handler. Both are separate files but the code is as follows:
<html>
<head>
<title>Login</title>
</head>
<body>
<h1> Welcome please Login: </h1>
<form action="LoginCreate.php" method="post">
Username: <input type=“name” name=“username” id="username"><br/>
Password: <input type="password” name=“password” id="password"><br/>
<input type="submit" value="Login"> <input type="submit" value="Create Account">
</form>
Then for the PHP fike: (please note I have not yet added code for checking against the database.)
<?
$db=sqlite_open("database.db");
$username = sqlite_escape_string($_POST["username"]);
$password = sqlite_escape_string($_POST["password"]);
if(isset($_POST['Create Account'])){
sqlite_query($db,"INSERT INTO username (name) VALUES ('$username')");
sqlite_query($db,"INSERT INTO password (password) VALUES ('$password')");
echo "<p> Account Created. <p>";
}
else if(isset($_POST['Login'])){
echo "<p> Login Successful. <p>";
}
sqlite_close($db);
?>
What should be causing the Data not to be Posting correctly, have I got the syntax wrong somewhere? I'm using MicroApache and getting no Errors popup in Chrome.
You need to add the name="action" attribute to your submit buttons and check
if(isset($_POST['action'])) {
if ($_POST['action'] == 'Create Account') {
} elseif ($_POST['action'] == 'Login') {
}
}
I have a Customer Details PHP page. To get to this page, the user either signs up with new details on signup.php or they log in on login.php.
Ive been told the best way to submit data and be redirected to the correct page is to use action="details.php" in the form, and then at the start of the details.php file use the values from the $_POST array to populate my SQL database.
However, I need to do the same sort of thing with the login.php code, so at the top of details.php there will be the code to enter the form data from signup.php and the verifying code from login.php.
Surely there is a way of doing the data submission directly from signup.php so there isnt two sets of PHP in the details.php file? If not how do i differentiate so that login only uses the login code and signup uses the submit code?
Common practice is to have PHP check for form data+possible redirect and after that form print
Example: (my common usage)(i merged login&signup into one file)
<?php
$error = "";
if( !empty($_POST['signup']) ){
//do signup
//$signup = assign true/false whether sign up was successfull or not
if( !$signup ){ //if signup wasnt successfull generate error
$error = "Sign up error.";
}
}
if( !empty($_POST['login']) ){
//do login
//$login = assign true/false whether login was successfull or not
if( !$login ){ //if login wasnt successfull generate error
$error = "Log in error.";
}
}
if( empty($error) ){
//there were no errors
header("Location: details.php"); //redirect to details.php
exit(); //send nothing else!
}
?>
<div class="error"><?php if(!empty($error)){ echo htmlspecialchars($error); /*escape*/ } ?></div>
<form action="#" method="POST">
<input type="hidden" name="signup" value="yes">
<!-- ...some other input fields... -->
<button type="submit">Sign Up</button>
</form>
<br>
<form action="#" method="POST">
<input type="hidden" name="login" value="yes">
<!-- ...some other input fields... -->
<button type="submit">Log In</button>
</form>
You could set a hidden field on each page as below:
<input type=hidden name='referrerpage' value='signup'>
AND
<input type=hidden name='referrerpage' value='login'>
and do:
if ($_POST['referrerpage']=='signup'){
//do this
} else{
//do this
}
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'm trying to create a form in which a user can upload an image with a title and description. All works fine except the image that isn't being moved to my server. Can anyone tell me what I'm doing wrong here? The folder which I'm trying to upload to has permissions set to 777.
The PHP code:
<?php
}
session_start();
if(!session_is_registered(myusername))
{
header("location:login.php");
}
// connect to the database
$conn=mysql_connect(*censored*) or die("Kan geen verbinding maken met de DB server");
mysql_select_db("frankkluytmans_",$conn) or die("Kan database niet selecteren");
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$pagid = mysql_real_escape_string(htmlspecialchars($_POST['pagid']));
$titlename = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$contentname = mysql_real_escape_string(htmlspecialchars($_POST['contentedit']));
$image = mysql_real_escape_string(htmlspecialchars("/gfx/".$_FILES["image"]["name"]));
// check to make sure both fields are entered
if ($titlename == '' || $pagid == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($pagid, $titlename, $contentname, $error);
}
else
{
if (move_uploaded_file($_FILES["image"]["tmp_name"], "/gfx/".$_FILES["image"] ["name"]))
{
// save the data to the database
mysql_query("INSERT frankkluytmans SET pagid='$pagid', title='$titlename', content='$contentname', image='$image'") or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
The form:
<form action="" method="post" enctype="multipart/form-data">
<h2>
<span>NEW</span>
<input type="text" name="pagid" value="" />
</h2>
<div class="pages-content">
<strong>Title: *</strong> <input type="text" name="title" /><br/>
<strong>Content: *</strong> <textarea name="contentedit"</textarea><br/>
<input type="file" name="image" id="image" />
<input type="submit" name="submit" value="Submit">
</div>
<script>
window.onload = function() {
CKEDITOR.replace( 'contentedit' );
console.log("editor werkt");
};
</script>
</form>
You PHP code is broken:
<?php
}
There is a mistake in your file, it start with a }
You have unwanted } at first line
Are you sure that the location is correct?
Try adding $_SERVER['DOCUMENT_ROOT'] in front of dir.. for example:
$image_dir = $_SERVER['DOCUMENT_ROOT']."/gfx/".$_FILES["image"]["name"];