Keep user on same page when they click submit on form - php

Hi the following code below is my comment form. I have included this file comments.php inside my blog posts. When the user clicks submit, they are taken to the blog page rather then kept on the blog article page they are viewing.
I have used this same code for different forms throughout my website, and those pages do not redirect, but rather they stay on the same page when the user clicks submit. Which is the correct way it should be.
I am wondering why this same code on the blog page is being redirected to blog category view when user clicks submit.
How can I prevent the redirection thanks.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "First Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
//email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
if (count($_POST)>0) echo "<h2>Form Submitted! Thank you <b>$name $lname</b>
for your comment</h2>";
?>
<hr>
<h3 style=" margin-top: 50px; ">Leave a comment</h3>
<h6><span class="error">* All fields required.</span></h6><br /><br />
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="text" placeholder="Name*" name="name" value="<?php echo $name;?>" required>
<span class="error"> <?php echo $nameErr;?></span>
<br><br>
</div>
</div>
<!--Email-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="email address*" value="<?php echo $email;?>"required>
<span class="error"> <?php echo $emailErr;?></span>
<br>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" style="margin-left: 17px;" name="comment" placeholder="Enter a comment*" rows="5" cols="40" required><?php echo $comment;?></textarea>
<br><br>
<div class="g-recaptcha" data-sitekey="6Lc3ZyUUAAAAAIT2Blrg4BseJK9KFc1Rx8VDVNs-"></div><br/>
<input type="submit" name="submit" value="Submit">
</div>
<hr>
</div>
</div>
</form>
<?php
//check if the form has been submitted
if(isset($_POST['submit'])){
/* Attempt MySQL server connection. */
<?php include 'view/conn.php'; ?>
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
// Escape user inputs for security
$Fname = mysqli_real_escape_string($link, $_REQUEST['name']);
$Email = mysqli_real_escape_string($link, $_REQUEST['email']);
$Message = mysqli_real_escape_string($link, $_REQUEST['comment']);
// attempt insert query execution
$sql = "INSERT INTO comments (Name, Email, Comment, Approved) VALUES
('$Fname', '$Email', '$Message', '0')";
if(mysqli_query($link, $sql)){
echo "<p>$Fname Your comment will appear once approved";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<?PHP
$email = $_POST["email"];
$to = "email#email.com";
$subject = "New Email Address for Mailing List";
$headers = "From: $email\n";
$message = "A visitor to your site has posted a comment on a blog post that requires approval.\n
Email Address: $email";
$user = "$email";
$usersubject = "Thank You";
$userheaders = "From: email#email.com\n";
$usermessage = "Thank you for comment at www.oryanm.waiariki.net.nz Geyserland SBA.";
mail($to,$subject,$message,$headers);
mail($user,$usersubject,$usermessage,$userheaders);
?>
<?php
echo "<h2>Comments</h2>";
<?php include 'view/conn.php'; ?>
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM comments WHERE Approved=1 ORDER by id DESC";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<p><b>Comment by:</b> " . $row["Name"]. "</p>" . "<p>" .
$row["Comment"]. "</p> " . "<i><b>Posted:</b> " . $row["Posted"]. "</i><br>
<hr>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Instead of php include, I used an iframe as a solution for this issue. Thanks for the help

pass one hidden field in your form
< input type="hidden" value="testRedirect">
and put redirect code on where you are redirect
and put redirect code on where you are redirect
if(isset($_REQUEST["hidden"]))
{
header('Location: http://www.example.com/your_form_view_page ');
exit;
}

Related

After I hit Submit on my PHP page nothing happens. The data should import into my php database

I created this signup page. The problem is when I click submit after I enter the information nothing happens. It just refreshes the same page. The info I enter should import into my database after I hit submit and display a thank you for signing up message after the submission. Please help. I'm trying to keep everything to single page by implementing the html and php code all on one page instead of 2 separate files.
<html>
<body>
<?php
$output_form = true; //declare a FLAG we can use to test whether or not to show form
$first_name = NULL;
$last_name = NULL;
$email = NULL;
if (isset($_POST['submit']) ) { //conditional processing based on whether or not the user has submitted.
$dbc = mysqli_connect('localhost', 'name', 'pswd', 'database')
or die('Error connecting to MySQL server.');
$first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$output_form = false; // will only change to TRUE based on validation
//Validate all form fields
if (empty($first_name)) {
echo "WAIT - The First Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($last_name)) {
echo "WAIT - The Last Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($email)) {
echo "WAIT - The Email field is blank <br />";
$output_form = true; // will print form.
}
if ((!empty($first_name)) && (!empty($last_name)) && (!empty($email))) {
//End of form validation
//This section establishes a connection to the mysqli database, and if it fails display error message
$query = "INSERT INTO quotes (first_name, last_name, email, " .
"VALUES ('$first_name', '$last_name', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
$to = 'email#email.com';
$subject = 'New Customer';
$msg = "$first_name $last_name\n" .
"Email: $email\n";
$mail = mail($to, $subject, $msg, 'From:' . $email);
if($mail){
header("Location: https://www.locate.com/blue.php".$first_name);
exit();
}
//Display the user input in an confirmation page
echo "<body style='margin-top: 100px; background-color: #f2f0e6;'><p style = 'color: #000000; text-align: center;font-size:300%; font-family:Arial, Helvetica, sans-serif;'><strong>Thanks for signing up!</strong></p><center><p style = 'color: #000000; text-align: center;font-size:200%; font-family:Arial, Helvetica, sans-serif;'>Contact us for any questions
</p>
</center>
</body>";
}//end of validated data and adding recored to databse. Closes the code to send the form.
} //end of isset condition. This closes the isset and tells us if the form was submitted.
else { //if the form has never been submitted, then show it anyway
$output_form = true;
}
if ( $output_form ) { //we will only show the form if the user has error OR not submitted.
?>
<div id="box">
<center><img src="../../images/duck.jpg" class="sign-up" alt="Sign Up"></center>
<br>
<p>Sign Up to get Discount Code</p><br>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<div>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" size="37" maxlength="37" value=" <?php echo $first_name; ?>" />
</div>
<div>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" size="37" maxlength="37" value="<?php echo $last_name; ?>" />
</div>
<div>
<label for="email">Email:</label>
<input type="text" id="email" name="email" size="37" maxlength="37" value="<?php echo $email; ?>" />
</div>
<div id="submit">
<input type="submit" name="Submit" value="Submit" />
</div>
</center>
</form>
</div>
<?php
}
?>
</body>
You are asking for $_POST['submit'] instead of $_POST['Submit']

How to send email to user input email address after click a submit button? In php

I'm super new at coding. This is the form page code
<?php
// Start the session
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$fnameErr = $emailErr = $addressErr = $countryErr = $stateErr = $suburbErr = "";
$fname = $email = $address = $country = $state = $suburb = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "Name is required";
} else {
$fname = test_input($_POST["fname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["country"])) {
$countryErr = "City is required";
} else {
$country = test_input($_POST["country"]);
}
if (empty($_POST["state"])) {
$stateErr = "State is required";
} else {
$state = test_input($_POST["state"]);
}
if (empty($_POST["suburb"])) {
$suburbErr = "State is required";
} else {
$suburb = test_input($_POST["suburb"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2 align="cemter">Check out</h2>
<p><span class="error">* required field</span></p>
Full Name: <input type="name" name="fname">
<span class="error">* <?php echo $fnameErr;?></span>
<br><br>
E-mail: <input type="email" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Address: <input type="text" name="address">
<span class="error">*<?php echo $addressErr;?></span>
<br><br>
Country: <input type="text" name="country">
<span class="error">*<?php echo $countryErr;?></span>
<br><br>
State: <input type="text" name="state">
<span class="error">*<?php echo $stateErr;?></span>
<br><br>
Suburb: <input type="text" name="suburb">
<span class="error">*<?php echo $suburbErr;?></span>
<br><br>
<form method="post" action="../mailer/index.php">
<input type="submit" name="submit" value="Purchase">
</form>
</body>
</html>
But after I fill up all the information and click submit, the page said cannot connect to SMTP sever host. The strange thing is, I can send email while run the phpmailer index.php alone. The form page php file and the mailer php file is in a different folder but same parent folder, is this the problem?
If one page works and another doesn't, and these are in different folders, then yes, that could be the problem. However, the solution is probably not to just move one of the files (which would probably give you other path related issues), but instead make sure that they both can reach the neccessary configuration (SMTP server host in this case).

Submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX

I want to create a submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX. I've tried W3C schools and a couple of step by step guides but still struggling. So far, I've written the HTML for and Validation and connected to my SQL database. However, I'm not sure what steps to take next. I'm new to coding and not sure what to do next...
<?php
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = "";
$name = $email = $phone = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Telephone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["register.php"])?>">
<fieldset>
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Phone: <input type="tel" name="phone" value="<?php echo $phone;?>">
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
<button type="submit"> Submit</button>
</fieldset>
</form>
</div>
I will do it simply like this:
Create an empty div before Form's fieldset:
<div class="col-xs-12 col-sm-9 col-md-8 col-lg-8 conForm">
<h4>Shoot a message!</h4>
**<div id="message"></div>**
<form method="post" action="php/contact.php" name="cform" id="cform">
<input name="name" id="name" type="text" class="col-xs-12 col-sm-6 col-md-6 col-lg-6" placeholder="Your name..." >
<input name="email" id="email" type="email" class=" col-xs-12 col-sm-6 col-md-6 col-lg-6 noMarr" placeholder="Your email..." >
<textarea name="comments" id="comments" cols="" rows="" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your message..."></textarea>
<input type="submit" id="submit" name="submit" class="submitBnt" value="Send message">
<div id="simple-msg"></div>
</form>
</div>
in PHP print message like this after email sent:
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
As you asked, i think you are totally new in coding world.so that's why i write full code in one page. create a .php file and paste this code
<html>
<head>
<script type="text/javascript">
function validateName() {
var name = document.getElementById('contact-name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false; }
if (!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
producePrompt('First and last name, please.','name-error', 'red');
return false; }
producePrompt('Valid', 'name-error', 'green');
return true;}
function validatePhone() {
var phone = document.getElementById('contact-phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false; }
if(phone.length != 10) {
producePrompt('Include area code.', 'phone-error', 'red');
return false; }
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false; }
producePrompt('Valid', 'phone-error', 'green');
return true;}
function validateEmail () {
var email = document.getElementById('contact-email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false; }
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false; }
producePrompt('Valid', 'email-error', 'green');
return true;}
function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 10;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false; }
producePrompt('Valid', 'message-error', 'green');
return true;}
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false; } else { }
}
function jsShow(id) {
document.getElementById(id).style.display = 'block'; }
function jsHide(id) {
document.getElementById(id).style.display = 'none';}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;}
</script>
</head>
<form action="" method="POST">
<div class="form-group">
<label for="contact-name">Name</label>
<input type="text" class="form-control" id="contact-name" name="name" placeholder="Enter your name.." onkeyup='validateName()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="tel" class="form-control" id="contact-phone" name="phone" placeholder="Ex: 1231231234" onkeyup='validatePhone()'>
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contact-email" name="email" placeholder="Enter Email" onkeyup='validateEmail()'>
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" id='contact-message' name='message' placeholder="Enter a brief message" onkeyup='validateMessage()'></textarea>
<span class='error-message' id='message-error'></span>
</div>
<button onclick='return validateForm()' name="submit" value="submit" class="btn btn-default">Submit</button>
<span class='error-message' id='submit-error'></span>
<span class='success-message' id='submit-success'></span>
<?php
if (isset($_POST['submit']) && (!empty($_POST['submit']))) {
$servername = "localhost";
$username = "root"; //change this to your username
$password = ""; //change this to your database password
$dbname = "db"; //change this to your database name
$name = "$_POST[name]";
$phone = "$_POST[phone]";
$email = "$_POST[email]";
$message = "$_POST[message]";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);}
//insert data into table named guestbook
$sql = "INSERT INTO guestbook (name, email, phone, message) VALUES ('$name', '$email', '$phone', '$message')";
if ($conn->query($sql) === TRUE) {
echo "<br/><font color=green>Your Comment Successfully Sent</font>";
} else {
echo "Error updating record: " . $conn->error; }
$conn->close();}
?>
</form>
</body>
</html>
In your DATABASE, create a database whatever you named but dont forget to change in php file $dbname = ""; and create table with these code:
CREATE TABLE guestbook
(
id int NOT NULL AUTO_INCREMENT,
name varchar(255),
email varchar(255),
phone varchar(255),
message varchar(255),
PRIMARY KEY (id)
);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);
}
$sql = "INSERT INTO MyGuests (name, email, phonenumber,comment)
VALUES ($name , $email ,$phone,$comment)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: ".$sql."<br>".$conn->error;
}
$conn->close();
Where put you $comment , $name and others and also configure you database name, password and database table.

Using Parameterized Queries/Prepared Statements

I'm new to php coding and have been told by others that I need to be using parameterized queries/prepared statements for my php scripts and MySQL database. I've looked at other examples of scripting these prepared statements and they usually refer to user login functions. My query is just a web form to capture user inputted data and store in database (SQL insert as opposed to SQL select). I am hoping someone can help me with how to script the php to prevent sql injections. Also hoping someone can let me know whether these prepared statements should also be used in php SQL Select scripts where I am only displaying database records on a form. Thanks in advance!
Here are the two php files I am using, the first is my database connection script:
<?php
DEFINE ('DB_USER', 'fakeuser');
DEFINE ("DB_PSWD", 'fakepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'newspaper');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
Web form PHP script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} else {
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die(mysqli_error($dbcon)); //and die('error inserting new record') ;
} // end of nested if statement
// else
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
UPDATED CODE with Prepared Statement 9/3/17: See bottom of script (Please tell me if you see any issues with this) Also I've commented out the !mysqli_query IF statement below the prepared statement as I thought this was now redundent, but please tell me if it is still required.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} else {
$name = test_input($_POST["Name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} else {
$email = test_input($_POST["Email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES (?,?,?,?)";
$stmt = mysqli_stmt_init($dbcon);
if (!mysqli_stmt_prepare($stmt,$sqlinsert)) {
echo "SQL error"; }
else {
mysqli_stmt_bind_param($stmt,"ssss",$fname, $femail, $fcomment, $fsubsciption);
mysqli_stmt_execute($stmt);
echo '1 record added to the database';
//if (!mysqli_query($dbcon, $sqlinsert)) {
//die(mysqli_error($dbcon));
} // end of nested IF statement
// else
//$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>

PHP ignoring if statements

I am having a very weird problem here, my if else statements just get ignored after I submit the form and all values entered or not entered goes through to the database.
Firstly, I pre populate all fields with info submitted during registration then users can edit and change their info - this works fine but I decided to add it as I don't know whether it might have a hand in this mystery error.
Here's my code to retrieve details, the variables holding retrieved values are echoed in their respective fields in the form.
<?php
include("connect.php");
$results = $conn->query("SELECT username, first_name,last_name, email,phone,address FROM users WHERE email='$user_logged'");
while ($row = $results->fetch_assoc()) {
$u_name = $row['username'];
$f_name = $row['first_name'];
$l_name = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
$address = $row['address'];
}
$results->free();
$conn->close();
?>
It's not checking for empty fields. Functions test_input and preg_match do not work alsko. The form just submits and database gets updated.
I have spent 2 days going through to look for where the error might be but I can't detect it.
<?php
$user_logged = $_SESSION['logged_in'];
if (isset($_POST['btnUpdate'])) {
include("connect.php");
$phoneErr = $f_nameErr = $l_nameErr = "";
$user_email = $first_name = $last_name = $phone_upadate = $address_updated = "";
if (empty($_POST["fname"])) {
$f_nameErr = "First Name is required";
} else {
$first_name = test_input($_POST["fname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $first_name)) {
$f_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$l_nameErr = "Last Name is required";
} else {
$last_name = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z ]*$/", $last_name)) {
$l_nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone No is required";
} else {
$phone_upadate = test_input($_POST['phone']);
if (!preg_match("/^[0-9]{0,18}$/", $phone_upadate)) {
$phoneErr = "Only numbers and white space allowed";
}
}
$user_email = $_POST['email'];
$address_updated = $_POST['txtaddress'];
$results = $conn->query("UPDATE users SET
first_name='$first_name',last_name='$last_name',
email='$user_email',phone='$phone_upadate',
address='$address_updated'
WHERE email='$user_logged'");
if ($results) {
header("Location: edit-info.php");
} else {
print 'Error : (' . $conn->errno . ') ' . $conn->error;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Here is my html code
<form action="edit-info.php" method="POST">
<?php $username_error="can't be changed"; ?>
<p>Username</p>
<p><input type="text" name="username" id="txtuser" value="<?php echo $u_name; ?>" readonly></input><span id="error"><?php echo $username_error?></span></p>
<p>First Name</p>
<p><input type="text" name="fname" id="txtuser" value="<?php echo $f_name; ?>"></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Last Name</p>
<p><input type="text" name="lname" id="txtuser" value="<?php echo $l_name; ?>" ></input><span id="error"><?php echo $l_nameErr;?></span></p>
<p>Email</p>
<p> <input type="text" name="email" id="txtuser" value="<?php echo $email; ?>" readonly></input><span id="error"><?php echo $f_nameErr;?></span></p>
<p>Phone</p>
<p><input type="text" name="phone" id="txtuser" value="<?php echo $phone; ?> " ></input></p>
<span id="error"><?php echo $phoneErr;?></span>
<p>Address</p>
<p><textarea id="txtaddress" name="txtaddress" cols="40" rows="10" ><?php echo $address; ?></textarea></p>
<p><input type="submit" name="btnUpdate" value="UPDATE" /></p>
</form>
You need to check the values of $phoneErr, $f_nameErr, $l_nameErr before you proceed UPDATE like this
if(empty($phoneErr) && empty($f_nameErr) && empty($l_nameErr)){
$results = $conn->query("UPDATE users SET first_name='$first_name',last_name='$last_name', email='$user_email',phone='$phone_upadate',address='$address_updated' WHERE email='$user_logged'");
}
Because when you have any validation error in empty or preg_match you are updating these values. And without checking these $phoneErr, $f_nameErr, $l_nameErr variables you are proceeding to UPDATE
You could try replacing
"/^[a-zA-Z ]*$/"
with
"/^[a-zA-Z ]+$/"
Notice we are replacing the multiplication sign with a summation sign.

Categories