how to pass the collected input to another page after self validate in php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
if($_SERVER["REQUEST_METHOD"] =="POST"){
$valid = true;
if(empty($_POST["forename"])){
$forenameErr = "Forename is required";
$valid = false; //false
} else {
$forename = test_input($_POST["forename"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["surname"])){
$surnameErr = "Surname is required";
$valid = false; //false
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["postalAddress"])){
$postalAddressErr =" Please enter postal address";
$valid = false; //false
} else {
$postalAddress = test_input($_POST["postalAddress"]);
}
if(empty($_POST["landLineTelNo"])){
$landLineTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$landLineTelNo = test_input($_POST["landLineTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$landLineTelNo)) {
$landLineTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["mobileTelNo"])){
$mobileTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$mobileTelNo = test_input($_POST["mobileTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$mobileTelNo)) {
$mobileTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
$valid = false; //false
} 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["sendMethod"])){
$sendMethodErr = "Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//if valid then redirect
if($valid){
header('Location: userdetail.php');
exit();
}
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error">* <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error">* <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> </span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> * <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" placeholder="example:012-3456789" value="<?php echo $mobileTelNo;?>" />
<span class="error"><?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>" placeholder="example:123#hotmail.com"/>
<span class="error"> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error">* <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="checkbox" value="check" id="agree" />
I have read and agree to the Terms and Conditions and Privacy Policy
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</fieldset>
</form>
</div>
</body>
</html>
here is my php form...
it can validate itself in the same page but couldn't pass the data to another php page....
here is my another php code...
<?php
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
echo "<p>Email: $email</p>";
echo "<p>Post Address: $postalAddress</p>";
echo "<p>Landline: $landLineTelNo</p>";
echo "<p>Mobile : $mobileTelNo</p>";
echo "<p>Contact method: $sendMethod";
?>
You can use $_SESSION variables.
PHP $_SESSIONS
PHP Sessions and Cookies
So after the users has been validated set $_SESSION['surname'] = $surname;
Then on the top of each page add session_start(); to the top.
Then Under that add
if (isset($_SESSION['surname'])) {
$surname = $_SESSION['surname'];
} else {
die();
}
View the PHP docs for a more thorough understanding.
You may also want to look into setting up a MYSQL database if you want users to be able to create accounts.
Edit: form page
if($valid){
$_SESSION['surname'] = $surname;
$_SESSION['postalAddress'] = $postalAddress;
header('Location: userdetail.php');
exit();
}
Related
I'm new to PHP and I just want to make some form like a basic form. But I have trouble in the values entered by the user. For example if they enter a empty field it should not redirect or if in the email they didn't enter a correct format the form should not redirect. But in my case it always redirect even though the input is invalid. Can you help me out on how can I stop redirecting to another page if the value entered by the user is invalid?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FG4</title>
</head>
<style>
.error {color: red}
</style>
<body>
<?php
$fname = $lname = $fgender = $mail = $dob = $address = "";
$fnameErr = $lnameErr = $genderErr = $mailErr = $dobErr = $addressErr = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if (empty($_GET["fname"])) {
$fnameErr = "Please enter your first name.";
} else {
$fname = input($_GET["fname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
$fnameErr = "Please enter a valid name";
}
}
if (empty($_GET["lname"])) {
$lnameErr = "Please enter your last name.";
} else {
$lname = input($_GET["lname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
$lnameErr = "Please enter a valid name";
}
}
if (empty($_GET["gender"])) {
$genderErr = "Please select a gender.";
} else{
$gender = input($_GET["gender"]);
}
if (empty($_GET["mail"])) {
$mailErr = "Please enter your email.";
} else {
$mail = input($_GET["mail"]);
// check if email contain gmail.com or yahoo.com
if (!preg_match("/#gmail.com|#yahoo.com/", $mail)) {
$mailErr = "Please enter a valid email.";
}
}
if (empty($_GET["dob"])) {
$dobErr = "Please select your date of birth.";
} else{
$lname = input($_GET["lname"]);
}
if (empty($_GET["address"])) {
$addressErr = "Please enter your address.";
} else {
$address = input($_GET["address"]);
// check if address contain the following characters
if (!preg_match(" /#|[0-9]|[a-z]|[A-Z]/ ",$address)) {
$address = "Please enter a valid address";
}
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="get" action="trial.php">
First Name: <input type="text" name="fname">
<span class="error">* <?php echo $fnameErr;?></span>
<br><br>
Larst Name: <input type="text" name="lname">
<span class="error">* <?php echo $lnameErr;?></span>
<br><br>
Gender: <input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Email: <input type="text" name="mail">
<span class="error">* <?php echo $mailErr;?></span>
<br><br>
Date of Birth: <input type="date" name="dob">
<span class="error">* <?php echo $dobErr;?></span>
<br><br>
Address: <br><textarea type="text" name="address" rows="5" cols="40"></textarea>
<span class="error"><?php echo $addressErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Here is the other code where it just print the values entered by the user
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// collect value of input field
$fname = $_GET['fname'];
$lname = $_GET['lname'];
$gender = $_GET['gender'];
$mail = $_GET['mail'];
$dob = $_GET['dob'];
$address = $_GET['address'];
echo "<h2> Final Output:</h2>";
echo "First Name :$fname";
echo "<br>";
echo "Last Name :$lname";
echo "<br>";
echo "Gender :$gender";
echo "<br>";
echo "Email :$mail";
echo "<br>";
echo "Date of Birth :$dob";
echo "<br>";
echo "Address :$address";
}
?>
</body>
</html>
There are many ways to do what you want.
One of them is to use a hidden form and submit it only if there is no error found after the validation.
Hence the amended code (based on your original code) will be:
trial.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FG4</title>
</head>
<style>
.error {color: red}
</style>
<body>
<?php
$fname = $lname = $fgender = $mail = $dob = $address = "";
$fnameErr = $lnameErr = $genderErr = $mailErr = $dobErr = $addressErr = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if (empty($_GET["fname"])) {
$fnameErr = "Please enter your first name.";
} else {
$fname = input($_GET["fname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
$fnameErr = "Please enter a valid name";
}
}
if (empty($_GET["lname"])) {
$lnameErr = "Please enter your last name.";
} else {
$lname = input($_GET["lname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
$lnameErr = "Please enter a valid name";
}
}
if (empty($_GET["gender"])) {
$genderErr = "Please select a gender.";
} else{
$gender = input($_GET["gender"]);
}
if (empty($_GET["mail"])) {
$mailErr = "Please enter your email.";
} else {
$mail = input($_GET["mail"]);
// check if email contain gmail.com or yahoo.com
if (!preg_match("/#gmail.com|#yahoo.com/", $mail)) {
$mailErr = "Please enter a valid email (only #gmail.com or #yahoo.com).";
}
}
if (empty($_GET["dob"])) {
$dobErr = "Please select your date of birth.";
} else{
$lname = input($_GET["lname"]);
}
if (empty($_GET["address"])) {
$addressErr = "Please enter your address.";
} else {
$address = input($_GET["address"]);
// check if address contain the following characters
if (!preg_match(" /#|[0-9]|[a-z]|[A-Z]/ ",$address)) {
$address = "Please enter a valid address";
}
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form id="form_id" method="get" action=#>
First Name: <input type="text" name="fname" value="<?php echo $_GET["fname"];?>">
<span class="error">* <?php echo $fnameErr;?></span>
<br><br>
Larst Name: <input type="text" name="lname" value="<?php echo $_GET["lname"];?>">
<span class="error">* <?php echo $lnameErr;?></span>
<br><br>
Gender: <input type="radio" name="gender" value="male"
<?php if ($_GET["gender"]=="male") { echo " checked ";} ?>
> Male
<input type="radio" name="gender" value="female"
<?php if ($_GET["gender"]=="female") { echo " checked ";} ?>
> Female
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Email: <input type="text" name="mail" value="<?php echo $_GET["mail"];?>">
<span class="error">* <?php echo $mailErr;?></span>
<br><br>
Date of Birth: <input type="date" name="dob" value="<?php echo $_GET["dob"];?>">
<span class="error">* <?php echo $dobErr;?></span>
<br><br>
Address: <br><textarea type="text" name="address" rows="5" cols="40"><?php echo $_GET["address"];?></textarea>
<span class="error"><?php echo $addressErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($fnameErr=="" && $lnameErr=="" && $genderErr=="" && $mailErr=="" && $dobErr=="" && $addressErr=="") { ?>
<form id="form_id2" method=GET action="trial2.php">
<input type=hidden name="fname" value="<?php echo $_GET["fname"];?>">
<input type=hidden name="lname" value="<?php echo $_GET["lname"];?>">
<input type=hidden name="gender" value="<?php echo $_GET["gender"];?>">
<input type=hidden name="mail" value="<?php echo $_GET["mail"];?>">
<input type=hidden name="dob" value="<?php echo $_GET["dob"];?>">
<textarea name=address style="display:none;"><?php echo $_GET["address"];?></textarea>
</form>
<script>
document.getElementById("form_id2").submit();
</script>
<?php } ?>
trial2.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// collect value of input field
$fname = $_GET['fname'];
$lname = $_GET['lname'];
$gender = $_GET['gender'];
$mail = $_GET['mail'];
$dob = $_GET['dob'];
$address = $_GET['address'];
echo "<h2> Final Output:</h2>";
echo "First Name :$fname";
echo "<br>";
echo "Last Name :$lname";
echo "<br>";
echo "Gender :$gender";
echo "<br>";
echo "Email :$mail";
echo "<br>";
echo "Date of Birth :$dob";
echo "<br>";
echo "Address :$address";
}
?>
</body>
</html>
I am creating a php form for data validation but there are some errors that I can't find.
When I submit the form the required notification is displayed. But when I reload the page then the required notification still remains. My code is:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
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["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";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
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
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the result when I first type the address in the browser.
This is the result when I enter an empty value in all the fields and submit the form. This will remain when I reload the page and until I close the browser tab and open a new tab and enter the url again.
You got error message when you reload after form submission. Try following code into your JS file or in JS code.
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
Hope this will help you!
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>
my form action is php_self so that it can validate the form...
what i want to do is after the form is submited, then the data is connect and send to sql....
i already import my sql table and it have a few data recorded inside the table....
so how can i connect to the sql??
and also where i should write my connect sql code in???
here is my php form code....
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
the userdetail.php is the page that shows the information that user submit...
so where and how i can insert the data in to sql....
You should write your SQL code within $valid.
Let me illustrate below:
Note: I've used default credentials: Hostname = localhost, username = root, password = '', database name = my_database.
You may refer to this: mysqli_connect()
if($valid){
echo "Valid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "my_database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO...."; // Your insert query
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
/* SQL code ends */
if ($query) { // Add this condition. Session should be written only when SQL query is successful
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
..........
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
} else {
echo "Unable to insert";
}
} else{
echo "Invalid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
}
Hope this helps.
after i submit the form, the data in the form is sent to sql...
the unfill text field sending nothing to the table....
how to auto assign the word "NULL" in sql if the user do not fill in anyhting in the form....
here is my php form code
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//connect to sql
if($valid){
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "chollerton");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = $sql = "INSERT INTO ct_expressedinterest (forename, surname, email, postalAddress, landLineTelNo, mobileTelNo ,sendMethod) VALUES ('$forename', '$surname', '$email', '$postalAddress', '$landLineTelNo', '$mobileTelNo' ,'$sendMethod')";
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}else {echo "Unable to insert";
}
} else{
//user did not submit form!
}
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
In your database, what's the default value of the particular field?
It should be set to NULL as default. In that case, if you're not inserting any data for that particular field, it will insert NULL.