why the validation did not work & jump to another page? - php

I wrote a customer_display.php to validate data (only First Name so far), but no matter First Name field is empty or not, the webpage will jump to customer_search.php & did not change information in database. why?
<?php include '../view/header.php';
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Control variables
$app_state = "empty"; //empty, processed, logged in
$valid = 0;
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
if(isset($_POST["first_name"]))
{
if (empty($_POST["first_name"])) {
$firstNameErr = "First name is required";
}
else {
$firstName = test_input($_POST["firstName"]);
if(strlen($firstName)>5){
$firstNameErr = "First name is too long";
}
else{
$valid++;
}
}
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
}
else {
$lastName = test_input($_POST["lastName"]);
$valid++;
}
if ($valid >= 2) {
$app_state = "processed";
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($app_state == "empty") {
?>
<!-- display a table of customer information -->
<h2>View/Update Customer</h2>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST" id="aligned">
<input type="hidden" value="update_customer">
<input type="hidden" name="customer_id"
value="<?php echo htmlspecialchars($customer['customerID']); ?>">
<label>First Name:</label>
<input type="text" name="first_name"
value="<?php echo htmlspecialchars($customer['firstName']); ?>">
<span class="error"><?php echo $firstNameErr;?></span><br>
<label>Last Name:</label>
<input type="text" name="last_name"
value="<?php echo htmlspecialchars($customer['lastName']); ?>"><br>
<label>Address:</label>
<input type="text" name="address"
value="<?php echo htmlspecialchars($customer['address']); ?>"
size="50"><br>
<label>City:</label>
<input type="text" name="city"
value="<?php echo htmlspecialchars($customer['city']); ?>"><br>
<label>State:</label>
<input type="text" name="state"
value="<?php echo htmlspecialchars($customer['state']); ?>"><br>
<label>Postal Code:</label>
<input type="text" name="postal_code"
value="<?php echo htmlspecialchars($customer['postalCode']); ?>"><br>
<label>Country:</label>
<select name="selected">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'tech_support';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if($conn->connect_error)
die('Could not connect: '. $conn->connect_error);
$selected= $conn->query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
$sql = $conn->query("select * from countries order by countryName");
if($selectedrow = $selected->fetch_assoc()){
echo "<option selected value='" . $selectedrow['countryName']."'>". $selectedrow['countryName']."</option>";
}
//echo "<select>";
while ($row = $sql->fetch_assoc()) {
echo "<option value ='". $row['countryName']."'>". $row['countryName']."</option>";
}
//echo "</select>";
$conn->close();
?>
</select><br>
<label>Phone:</label>
<input type="text" name="phone"
value="<?php echo htmlspecialchars($customer['phone']); ?>"><br>
<label>Email:</label>
<input type="text" name="email"
value="<?php echo htmlspecialchars($customer['email']); ?>"
size="50"><br>
<label>Password:</label>
<input type="text" name="password"
value="<?php echo htmlspecialchars($customer['password']); ?>"><br>
<label> </label>
<input type="submit" value="Update Customer"><br>
</form>
<p>Search Customers</p>
</body>
</html>
<?php
}
elseif ($app_state == "processed") {
if ($firstName == "Vincent") {
$app_state = "Logged in";
}
}
if ($app_state == "Logged in") {
echo("Logged in<br> Hello Vincent</body></html>");
}
?>
<?php include '../view/footer.php'; ?>
index.php(to process the data):
<?php
require('../model/database.php');
require('../model/customer_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'search_customers';
}
}
//instantiate variable(s)
$last_name = '';
$customers = array();
if ($action == 'search_customers') {
include('customer_search.php');
} else if ($action == 'display_customers') {
$last_name = filter_input(INPUT_POST, 'last_name');
if (empty($last_name)) {
$message = 'You must enter a last name.';
} else {
$customers = get_customers_by_last_name($last_name);
}
include('customer_search.php');
} else if ($action == 'display_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$customer = get_customer($customer_id);
include('customer_display.php');
} else if ($action == 'update_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$first_name = filter_input(INPUT_POST, 'first_name');
//echo $first_name;
$last_name = filter_input(INPUT_POST, 'last_name');
$address = filter_input(INPUT_POST, 'address');
$city = filter_input(INPUT_POST, 'city');
$state = filter_input(INPUT_POST, 'state');
$postal_code = filter_input(INPUT_POST, 'postal_code');
$country_name = $_POST["selected"];
$phone = filter_input(INPUT_POST, 'phone');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
//if(!$valid_fname == null){require ('customer_display.php');};
//echo $country_name;
$country_code = get_countryCode($country_name);
update_customer($customer_id, $first_name, $last_name,
$address, $city, $state, $postal_code, $country_code,
$phone, $email, $password);
include('customer_search.php');
}
?>

You have no name attribute with the value of 'action', so your update never happens.
<form action="" method="POST">
<input type="hidden" value="update_customer">
<!-- rest of the form -->
</form>
Edited for clarity.

Related

How do i verify query record with form input

In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance

php form 2 step confirmation

i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>

using multiple html forms to update mysql data using php

My code is given below (didn't include any html, no error/warning/notice). The program executes fine. The only problem I have is when I try to change the member_id and date fields in database- it doesn't work! As you can see I have used separate names for same fields mmid (used in the form) for member_id and dd (used in the form) for today. So, when user enters a different value it is assigned to mmid and dd while keeping the original values to member_id and dd allowing me to properly execute the update query. All other fields update is done as expected. None of the fields in the db is primary/unique/index. Could you please help me find where the problem is?
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$memberErr = $employeeErr = $dateErr = $blankfieldErr ="";
$mmid = $dd = $member_id = $employee_id = $paid_installment = $savings_deposit = $late_fee = $today = $dayx = $monthx = $yearx = "";
if (isset($_POST['SubmitFirst']))
{
if (empty($_POST["member_id"])) {
$memberErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$member_id = test_input($_POST["member_id"]);
}
if(!empty($_POST["dayx"]))
{
$dayx = test_input($_POST["dayx"]);
}
if(!empty($_POST["monthx"]))
{
$monthx = test_input($_POST["monthx"]);
}
if(!empty($_POST["yearx"])) // if all of them are selected
{
$yearx = test_input($_POST["yearx"]);
}
if(!empty($_POST["dayx"]) and !empty($_POST["monthx"]) and !empty($_POST["yearx"])){
$today= $yearx. "-" . $monthx. "-" . $dayx; }
else { $dateErr = "আপনি দিন / মাস / বছর লিখতে ভুলে গেছেন"; }
}
if (isset($_POST['Submit']))
{
echo $mmid;
echo " ";
echo $dd;
if (empty($_POST["mmid"])) {
$memberErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$mmid = test_input($_POST["mmid"]);
}
if (empty($_POST["dd"])) {
$dateErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$dd = test_input($_POST["dd"]);
}
if (empty($_POST["employee_id"])) {
$employeeErr = "আপনি কর্মীর আইডি দিতে ভুলে গেছেন";
} else {
$employee_id = test_input($_POST["employee_id"]);
}
if (empty($_POST["paid_installment"]) and empty($_POST["savings_deposit"]) and empty($_POST["late_fee"])) {
$blankfieldErr = "আপনি installment/savings/late_fee দিতে ভুলে গেছেন";
} else {
$paid_installment = test_input($_POST["paid_installment"]);
$savings_deposit = test_input($_POST["savings_deposit"]);
$late_fee = test_input($_POST["late_fee"]);
}
$servername = "localhost";
$username = "xxxxx";
$password = "yyyyy";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to UPDATE a record
$sql1 = "UPDATE daily_collection set date='$dd', member_id='$mmid', employee_id='$employee_id', paid_installment='$paid_installment', savings_deposit='$savings_deposit', late_fee='$late_fee' where member_id='$member_id' and date='$today'";
if ($result1=mysqli_query($conn,$sql1)) {
echo "<h2>". "সাবাস আপনি ঠিকভাবে তথ্য রেকর্ড করেছেন!". "</h2>";
} else {
echo "<h2>"."প্রোগ্রামে কিছু একটা সমস্যা হয়েছে, সুদিন স্যার-এর সাথে যোগাযোগ করুন ". "</h2>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
সদস্যর আইডি <input type="text" name="member_id" value="<?php echo $member_id;?>" size="50">
<span class="error"> <?php echo $memberErr;?></span>
<br><br>
তারিখ দিন <input type="text" name="dayx" value="<?php echo $dayx;?>" size="10"> মাস <input type="text" name="monthx" value="<?php echo $monthx;?>" size="10"> বছর <input type="text" name="yearx" value="<?php echo $yearx;?>" size="10">
<span class="error"> <?php echo $dateErr;?></span>
<br><br>
<center><input type="submit" name="SubmitFirst" value="SubmitFirst"></center><br>
</form>
<?php
if(isset($_POST['SubmitFirst']) and $member_id!="" and $today!="")
{
$servername = "localhost";
$username = "xxxxx";
$password = "yyyyy";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="select * from daily_collection where member_id='$member_id' and date='$today'";
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$dd=$row["0"];
$mmid=$row["1"];
$employee_id=$row["2"];
$paid_installment=$row[3];
$savings_deposit=$row[4];
$late_fee=$row[5];
}
echo $member_id;
echo " ";
echo $today;
}
else { echo "no such entry found";}
?>
<center><h2>দৈনিক কালেকশন এন্ট্রি ফর্ম</h2></center>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
সদস্যর আইডি <input type="text" name="mmid" value="<?php echo $mmid;?>" size="50">
<span class="error"> <?php echo $memberErr;?></span>
<br><br>
কর্মীর আইডি <input type="text" name="employee_id" value="<?php echo $employee_id;?>" size="50">
<span class="error"> <?php echo $employeeErr;?></span>
<br><br>
কিস্তির টাকা <input type="text" name="paid_installment" value="<?php echo $paid_installment;?>" size="50">
<br><br>
সঞ্চয় <input type="text" name="savings_deposit" value="<?php echo $savings_deposit;?>" size="50">
<br><br>
লেট ফী <input type="text" name="late_fee" value="<?php echo $late_fee;?>" size="50">
<span class="error"> <?php echo $blankfieldErr;?></span>
<br><br>
তারিখ <input type="text" name="dd" value="<?php echo $dd;?>" size="10">
<span class="error"> <?php echo $dateErr;?></span>
<br><br>
<center><input type="submit" name="Submit" value="Submit"></center><br>
</form>
<?php
}
if(!empty($_POST['Submit']))
{
}
?>
Inside if (isset($_POST['Submit']))
{ this block you have print $mmid, As $mmid is not set here so it will not print anything. To get the exact update query please echo $sql1
Update below part by
while ($row=mysqli_fetch_row($result))
{
$dd=$row["0"];
$mmid=$row["1"];
$employee_id=$row["2"];
$paid_installment=$row[3];
$savings_deposit=$row[4];
$late_fee=$row[5];
}
**while ($row=mysqli_fetch_assoc($result))** or instead of $row["0"] put $row[0] or exact column name like $row['date']

PHP variables not being passed to the next page

So I have two files. The first is the index.php in the root folder the other is an index.php found in a controller folder named post_link. I want to pass email, password, and action from the form in index.php of the root to the index.php of post_link but its just passing empty values when I try to get them using, filter_input(INPUT_POST, 'value'). How do I pass variables from index.php of the root to the index.php of post_link?
index.php of the root:
<?php
session_start();
require_once('model/fields.php');
// Add header
include '/view/header.php';
// Add fields with optional initial message
$validate = new Validate();
$fields = $validate->getFields();
$fields->addField('first_name');
$fields->addField('last_name');
$fields->addField('password');
$fields->addField('email', 'Must be a valid email address.');
// Makes sure the pages uses a secure connection
if(!isset($_SERVER['HTTPS'])) {
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: " . $url);
exit();
}
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = 'login';
$email = '';
} else {
$action = strtolower($action);
}
if ($email == '') {
$login_message = 'Login or register if you are a new user.';
}
else {
$login_message = '<span class="error">Invalid email.</span>';
}
?>
<main>
<h2>Login</h2>
<form action="post_list" method="post" class="aligned">
<fieldset>
<legend>Customer Login</legend>
<input type="hidden" name="action" value="login">
<label>Email:</label>
<input type="text" class="text" name="email">
<br>
<label>Password: </label>
<input type="text" class="text" name="password">
<br>
<label> </label>
<input type="submit" value="Login">
<br>
</fieldset>
</form>
<form action="." method="post" class="aligned">
<fieldset>
<legend>Customer Registration</legend>
<input type="hidden" name="action" value="reset">
<label>You must be registered to view posts</label>
<input type="submit" value="Register here">
</fieldset>
</form>
<p><?php echo $login_message; ?></p>
</main>
<?php include 'view/footer.php'; ?>
index.php of the controller:
<?php
// session_start();
require_once('../model/database.php');
require_once('../model/customers_db.php');
require_once('../model/validate.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = 'login';
$email = '';
} else {
$action = strtolower($action);
}
switch ($action) {
case 'login':
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST,'password');
if (is_valid_customer_login($email)) {
$_SESSION['is_valid_customer'] = true;
$customer = get_customer($email);
$first_name = $customer['firstName'];
$last_name = $customer['lastName'];
if (is_valid_customer_login_password($email, $password)) {
include('../view/customer_menu.php');
} else {
$login_message = '<span class="error">Invalid password.</span>';
include('../index.php');
}
} else {
if ($email == '') {
$login_message = 'Login or register if you are a new customer.';
}
else {
$login_message = '<span class="error">Invalid email.</span>';
}
}
break;
case 'reset':
// Reset values for variables
$first_name = '';
$last_name = '';
$email = '';
$password ='';
// Load view
include 'view/register.php';
break;
case 'register':
// Copy form values to local variables
$first_name = trim(filter_input(INPUT_POST, 'first_name'));
$last_name = trim(filter_input(INPUT_POST, 'last_name'));
$email = trim(filter_input(INPUT_POST, 'email'));
$password =trim(filter_input(INPUT_POST, 'password'));
// Validate form data
$validate->text('first_name', $first_name);
$validate->text('last_name', $last_name);
$validate->email('email', $email);
$validate->password('password', $password);
// Load appropriate view based on hasErrors
if ($fields->hasErrors()) {
include 'view/register.php';
} else {
add_customer($first_name, $last_name, $email, $password);
include 'view/customer_menu.php';
}
break;
case 'logout':
$_SESSION = array(); // Clear all session data from memory
session_destroy(); // Clean up the session ID
$login_message = 'You have been logged out.';
include('view/login.php');
break;
}
?>
This ain't gonna work this way, You have to use the action as "post_list/index.php". So modify your form as:
<form action="post_list/index.php" method="post" class="aligned">
<fieldset>
<legend>Customer Login</legend>
<input type="hidden" name="action" value="login">
<label>Email:</label>
<input type="text" class="text" name="email">
<br />
<label>Password: </label>
<input type="text" class="text" name="password">
<br>
<label> </label>
<input type="submit" value="Login">
<br>
</fieldset>

Display PHP Form Validation Results on Same Page

I'm sure the initial reaction is going to be something like, "Doesn't this guy have Google?" Yes, I'll admit this does seem like a pretty basic concept and I've tried and tried to wrap my head around it, looked up all manner of posts and articles on the topic, etc., but all to no avail. Perhaps you can point me in the right direction?
I have a basic contact form (contact.html) that I run with an external PHP script (contact.php). Here's the HTML form code:
<form id="form1" action="contact.php" method="post">
<div class="form1">
<label>Your Name:</label>
<span><input type="text" name="name" /></span>
</div>
<div class="form1">
<label>Your School:</label>
<span><input type="text" name="school" /></span>
</div>
<div class="form1">
<label>Phone Number:</label>
<span><input type="text" name="phone" /></span>
</div>
<div class="form1">
<label>E-Mail Address:</label>
<span><input type="text" name="email" /></span>
</div>
<div class="form3">
<span><textarea cols="1" rows="1" name="message"></textarea></span>
</div>
<div class="wrapper">
<input class="submit" type="image" src="images/contact_submit.png" name="submit" alt="Submit" />
</div>
</form>
The PHP script validates that all of the fields were entered and then processes the form:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Validate the name:
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
echo "You forgot to enter your name.<br>";
}
//Validate the school:
if (!empty($_POST['school'])) {
$school = $_POST['school'];
} else {
echo "You forgot to enter your school.<br>";
}
//Validate the e-mail:
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
echo "You forgot to enter your e-mail.<br>";
}
//Validate the message:
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
echo "You forgot to enter a message.";
}
if (!empty($_POST['name']) && !empty($_POST['school']) && !empty($_POST['email']) && !empty($_POST['message'])) {
$phone = $_POST['phone'];
$body = "$name\n$school\n$phone\n$email\n\n$message";
mail("***", "PAL Website - Message from a Visitor", $body);
header("Location: confirm.html");
}
}
?>
Everything works great and the form is validated and processed as intended. However, I REALLY want to set it up so that the error messages are displayed on the same page or at least have the form refreshed with the error messages included.
I've seen this done in other demonstrations (Larry Ullman's book, for example), but still can't quite figure out how to make it happen. Can you please offer advice? What's the simplest way to go about it?
Here's the page URL, if it helps: http://www.712jefferson.org/pal/contact.html
Thank you!
I'd use jQuery for this.
Modifications to be made:
in HTML:
add id to your input fileds, so you can "grab" them with jQuery (You can see the usage in the $.post method below).
<form id="form1" action="contact.php" method="post">
<div class="form1">
<label>Your Name:</label>
<span><input id="name" type="text" name="name" /></span>
</div>
<div class="form1">
<label>Your School:</label>
<span><input id="school" type="text" name="school" /></span>
</div>
<div class="form1">
<label>Phone Number:</label>
<span><input id="phone" type="text" name="phone" /></span>
</div>
<div class="form1">
<label>E-Mail Address:</label>
<span><input id="email" type="text" name="email" /></span>
</div>
<div class="form3">
<span><textarea id="message" cols="1" rows="1" name="message"></textarea></span>
</div>
<div class="wrapper">
<input class="submit" type="image" src="images/contact_submit.png" name="submit" alt="Submit" />
</div>
</form>
in PHP:
if there is no error in validation echo this: "success"
if (!empty($_POST['name']) && !empty($_POST['school']) && !empty($_POST['email']) && !empty($_POST['message'])) {
echo "success";
$phone = $_POST['phone'];
$body = "$name\n$school\n$phone\n$email\n\n$message";
mail("***", "PAL Website - Message from a Visitor", $body);
header("Location: confirm.html");
}
Attach jQuery library to your site and use the code below in your HTML file inside brackets or in an external *.js file attached to Your site.
In Your HTML file's section use this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
jQuery script:
$('#form1').submit(function() {
event.preventDefault();
$.post("contact.php", {name: $("#name").val(), school: $("#school").val(), phone: $("#phone").val(), email: $("#email").val(), message: $("#message").val()}, function(data){
if(data !="success"){
alert(data);
}
});
});
This will give Your error messages in a alert window and Your site won't reload if I'm not mistaken.
There are many ways of doing this so this is a opinion based question which will get you several ways of accomplishing this.
You could do an ajax request to submit the data that way no reloading of the page and on the success of the call if any errors are in the response show the errors near the input that caused the error. This would require the use of javascript and setting a hidden element to the error and displaying it or generating the element containing the error and appending it to the DOM.
do as Amal Murali shows and put the html and validation script in the same script file and output the errors right away, or even better echo the errors near the inputs that caused them
yet another way would be to have contact.php do the validation and then on invalid data print out contact.html and again put the errors near the inputs.
<?php
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $genderErr = $courseErr = "";
$firstname = $lastname = $username = $password = $gender = $comments = "";
$course = array();
//var_dump($_POST['gender']);
//exit;
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$variables = array();
$variables = initialize();
$errors = array();
$errors = validate_errors($variables);
if (count($errors) == 0) {
//database operation
//exit;
}
}
function clean($data) {
$data = strip_tags(htmlspecialchars(stripslashes(trim($data))));
//trim :- Strip whitespace (or other characters) from the beginning and end of a string
//The stripslashes() function removes backslashes.Prevents XSS
//htmlspecialchars :- Converts the predefined characters "<" (less than) and ">" (greater than) to HTML entities:< (less than) becomes < and > (greater than) becomes >Helps in preventing XSS
//The strip_tags() function strips a string from HTML, XML, and PHP tags.
return $data;
}
function initialize(){
$var = array();
$var['firstname'] = clean($_POST['firstname']);
$var['lastname'] = clean($_POST['lastname']);
$var['username'] = clean($_POST['username']);
$var['password'] = clean($_POST['password']);
if(!empty($_POST['gender'])) { //if-else condition is used because here we don't type in any data,but just select data
$var['gender'] = $_POST['gender'];
} else {
$var['gender'] = '';
}
//var_dump($_POST[gender]);
if(!empty($_POST['course'])) { //if-else condition is used because here we don't type in any data,but just select data
$var['course'] = $_POST['course'];
} else {
$var['course'] = '';
}
$var['comments'] = clean($_POST['comments']);
return $var;
}
function validate_errors($var) { //is an array being passed into this function??have a look at arg of validateFirstName.
$errors = array();
$errors['firstname'] = validateFirstName($var['firstname']);//should return error string or ''
$errors['lastname'] = validateLastname($var['lastname']);
$errors['username'] = validateUserName($var['username']);
$errors['password'] = validatePassword($var['password']);
$errors['gender'] = validateGender($var['gender']);
$errors['course'] = validateCourse($var['course']);
$errors['comments'] = validateComments($var['comments']);
return $errors;
}
function validateFirstName($fname){
if(empty($fname)){
global $firstnameErr;
$firstnameErr = "First name is required";
return $firstnameErr;
} else if (!preg_match("/^[a-zA-Z ]*$/", $fname)){ // check if name only contains letters and whitespace.Performs a regular expression match
global $firstnameErr;
$firstnameErr = "Only letters are allowed";
return $firstnameErr;
} else {
global $firstname;
$firstname = $fname;
return '';
}
}
function validateLastName($lname){
if(empty($lname)){
return '';
} else if (!preg_match("/^[a-zA-Z ]*$/", $lname)) { // check if name only contains letters and whitespace,performs a regular expression match
global $lastnameErr;
$lastnameErr = "Only letters are allowed";
return $lastnameErr;
} else {
global $lastname;
$lastname = $lname;
return '';
}
}
function validateUserName($uname) {
if(empty($uname)) {
global $usernameErr;
$usernameErr = "Username is required";
return $usernameErr;
} else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $uname)){ // checks if username contains only letters and digits
global $usernameErr;
$usernameErr = "Only letters and digits are allowed";
return $usernameErr;
} else {
global $username;
$username = $uname;
return '';
}
}
function validatePassword($pword){
if(empty($pword)) {
global $passwordErr;
$passwordErr = "Password is required";
return $passwordErr;
} else if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pword) === 0) {
global $passwordErr;
$passwordErr = "Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit";
return $passwordErr;
} else {
global $password;
$password = $pword;
return '';
}
}
function validateGender($gen){
if(empty($gen)) {
global $genderErr;
$genderErr = "Gender is required";
return $genderErr;
} else {
global $gender;
$gender = $gen;
return '';
}
}
function validateCourse($cour){
if(empty($cour)) {
global $courseErr;
$courseErr = "Select atleast one";
return $courseErr;
} else {
global $course;
$course = $cour;
return '';
}
}
function validateComments($comm){
if(empty($comm)) {
return '';
} else {
global $comments;
$comments = $comm;
return '';
}
}
//renderform();
?>
<html>
<head>
<title>Sample Form</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname; ?>" /><span class="error">* <?php echo $firstnameErr; ?></span><br/><br/>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname; ?>" /><span class="error"> <?php echo $lastnameErr; ?></span><br/><br/>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php echo $username; ?>" /><span class="error">* <?php echo $usernameErr; ?></span><br/><br/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" /><span class="error">* <?php echo $passwordErr; ?></span><br/><br/>
Gender:
<label for="male">Male</label>
<input type="radio" name="gender" id="male" <?php if (isset($gender) && $gender == "male") echo "checked"; ?> value="male" />
<label for="female">Female</label>
<input type="radio" name="gender" id="female" <?php if (isset($gender) && $gender == "female") echo "checked"; ?> value="female" /><span class="error">* <?php echo $genderErr; ?></span><br/><br/>
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("PHP",$_POST["course"]))){echo "checked";}?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("HTML",$_POST["course"]))){echo "checked";}?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("CSS",$_POST["course"]))){echo "checked";}?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php if((!empty($_POST["course"])&& in_array("Javascript",$_POST["course"]))){echo "checked";}?> value="Javascript" /><span class="error">* <?php echo $courseErr; ?></span><br/><br/>
<label for="comments">Comments:</label><br/>
<textarea name="comments" rows="4" cols="20" id="comments"/><?php echo $comments; ?></textarea><br/><br/>
<input type = "submit" value="Submit" name="submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo "Firstname:" . $firstname;
echo "<br>";
echo "Lastname:" . $lastname;
echo '<br>';
echo "Username:" . $username;
echo '<br>';
echo "Password:" . $password;
echo '<br>';
echo "Gender:" . $gender;
echo '<br>';
global $string;
$string = implode(",",$course);
echo "Course(/s):" . $string;
echo '<br>';
echo "Comments:" . $comments;
echo '<br>';
?>
</body>
</html>
code of index.php(This file is run first)
<?php
define('PROJECT',$_SERVER['DOCUMENT_ROOT'].'PhpSample');
include (PROJECT.'/utilities.php');
include ('constant.php');
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$errors = validate_errors($variables);
$counter = 0;
foreach ($errors as $value) {
if ($value === '') {
$counter++;
}
}
//if there are no errors
if ($counter == 7) {
//database operation
$con = mysqli_connect($host, $user, $pword);
if (!$con) {
echo 'Error connecting to database. Please try again later';
exit;
}
$val = cleanandinsert($variables,$con,$dbname);
mysqli_close($con);
if(!$val){
echo 'Could not register. Please try again later';
exit;
}
header("Location:http://localhost/PhpSample/target.php?vals=" . urlencode(serialize($variables)));
exit;
}
}
include('myform.phtml');
?>
Code of target.php
<?php
include 'process.php';
$Values= unserialize(urldecode($_GET['vals']));
echo "<h2>Your Input:</h2>";
echo "Firstname:".$Values['firstname'];
echo "<br>";
echo "Lastname:".$Values['lastname'] ;
echo '<br>';
echo "Username:".$Values['username'] ;
echo '<br>';
echo "Password:".$Values['password'] ;
echo '<br>';
echo "Gender:".$Values['gender'] ;
echo '<br>';
if (!empty($Values['course'])) {
$string = implode(',', $Values['course']);
} else {
$string = "";
}
echo "Course(/s):" . $string;
echo '<br>';
echo "Comments:".$Values['comments'] ;
echo '<br>';
?>
Code of constant.php
<?php
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $passwordErr = $genderErr = $courseErr = "";
$firstname = $lastname = $username = $password = $gender = $comments = "";
$course = array();
$variables = initialize();
$host = 'localhost';
$user = 'root';
$pword = '';
$dbname = 'mydb';
$tablename = 'userdata';
?>
Code of myform.phtml
<html>
<head>
<title>Sample Form</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<p><span class="error">* required field.</span></p>
<form method="post" action="./index.php">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" value="<?php if (isset($variables['firstname']) ? print_r($variables['firstname']) : '') ; ?>" /><span class="error">* <?php if (isset($errors['firstname']) ? print_r($errors['firstname']) : '') ; ?></span><br/><br/>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" value="<?php if (isset($variables['lastname']) ? print_r($variables['lastname']) : '') ; ?>" /><span class="error"> <?php if (isset($errors['lastname']) ? print_r($errors['lastname']) : '') ; ?></span><br/><br/>
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php if (isset($variables['username']) ? print_r($variables['username']) : '') ; ?>" /><span class="error">* <?php if (isset($errors['username']) ? print_r($errors['username']) : '') ; ?></span><br/><br/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" /><span class="error">* <?php if (isset($errors['password']) ? print_r($errors['password']) : '') ; ?></span><br/><br/>
Gender:
<label for="male">Male</label>
<input type="radio" name="gender" id="male" <?php if (isset($variables['gender']) && ($variables['gender'] == "male")) echo "checked"; ?> value="male" />
<label for="female">Female</label>
<input type="radio" name="gender" id="female" <?php if (isset($variables['gender']) && ($variables['gender'] == "female")) echo "checked"; ?> value="female" /><span class="error">* <?php if (isset($errors['gender']) ? print_r($errors['gender']) : '') ; ?></span><br/><br/>
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php echo getChecked("PHP") ?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php echo getChecked("HTML") ?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php echo getChecked("CSS") ?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php echo getChecked("Javascript") ?> value="Javascript" /><span class="error">* <?php if (isset($errors['course']) ? print_r($errors['course']) : '') ; ?></span><br/><br/>
<label for="comments">Comments:</label><br/>
<textarea name="comments" rows="4" cols="20" id="comments"/><?php if (isset($variables['comments']) ? print_r($variables['comments']) : '') ; ?></textarea><br/><br/>
<input type = "submit" value="Submit" name="submit">
</form>
Code of utilities.php
<?php
/**
* It cleans the variable and returns variable free from cross site cripting.
* #return variable free from whitespaces,stripped of slashes,tags.
*/
function clean($data, $ishtmltype = FALSE) {
if ($ishtmltype) { //for database operation
$data = htmlspecialchars(stripslashes(trim($data)));
return $data;
}
$data = strip_tags(htmlspecialchars(stripslashes(trim($data))));
return $data;
}
/**
* It returns an array of variables which are cleansed with the help of "clean()"
* #return $var array
*/
function initialize() {
$var = array();
$var['firstname'] = isset($_POST['firstname']) ? clean($_POST['firstname']) : '';
$var['lastname'] = isset($_POST['lastname']) ? clean($_POST['lastname']) : '';
$var['username'] = isset($_POST['username']) ? clean($_POST['username']) : '';
$var['password'] = isset($_POST['password']) ? $_POST['password'] : '';
if (!empty($_POST['gender'])) {
$var['gender'] = $_POST['gender'];
} else {
$var['gender'] = '';
}
//var_dump($_POST[gender]);
if (!empty($_POST['course'])) {
$var['course'] = $_POST['course'];
} else {
$var['course'] = '';
}
$var['comments'] = isset($_POST['comments']) ? clean($_POST['comments']) : '';
return $var;
}
/**
* It returns an array of error variables which have error messages in them
* #param type $var array
* #return $errors array
*/
function validate_errors($var) {
$errors = array();
$errors['firstname'] = validateFirstName($var['firstname']); //should return error string or ''
$errors['lastname'] = validateLastname($var['lastname']);
$errors['username'] = validateUserName($var['username']);
$errors['password'] = validatePassword($var['password']);
$errors['gender'] = validateGender($var['gender']);
$errors['course'] = validateCourse($var['course']);
$errors['comments'] = validateComments($var['comments']);
return $errors;
}
/**
* It returns an error message, if any, in the first name
* #param type $fname
* #return string or null if not found
*/
function validateFirstName($fname) {
if (empty($fname)) {
$firstnameErr = "First name is required";
return $firstnameErr;
} else if (!preg_match("/^[a-zA-Z']*$/", $fname)) { // check if name only contains letters and whitespace.Performs a regular expression match
$firstnameErr = "Only letters are allowed";
return $firstnameErr;
}
else if (strlen($fname) < 3){
$firstnameErr = "Atleast 3 characters";
return $firstnameErr;
}
else if (strlen($fname) > 60){
$firstnameErr = "Not more than 60 characters";
return $firstnameErr;
}
return '';
}
/**
* It returns an error message, if any, in the last name
* #param type $lname
* #return string or null if not found
*/
function validateLastName($lname) {
if (empty($lname)) {
return '';
} else if (!preg_match("/^[a-zA-Z ]*$/", $lname)) { // check if name only contains letters and whitespace,performs a regular expression match
$lastnameErr = "Only letters are allowed";
return $lastnameErr;
}
else if (strlen($lname) > 60){
$firstnameErr = "Not more than 60 characters";
return $firstnameErr;
}
return '';
}
/**
* It returns an error message, if any, in the user name
* #param type $uname
* #return string or null if not found
*/
function validateUserName($uname) {
if (empty($uname)) {
$usernameErr = "Username is required";
return $usernameErr;
} else if (!preg_match("/^[a-zA-Z0-9 ]*$/", $uname)) { // checks if username contains only letters and digits
$usernameErr = "Only letters and digits are allowed";
return $usernameErr;
}
else if (strlen($uname) < 3){
$firstnameErr = "Atleast 3 characters";
return $firstnameErr;
}
else if (strlen($uname) > 60){
$firstnameErr = "Not more than 60 characters";
return $firstnameErr;
}
return '';
}
/**
* It returns an error message, if any, in the password
* #param type $pword
* #return string or null if not found
*/
function validatePassword($pword) {
if (empty($pword)) {
$passwordErr = "Password is required";
return $passwordErr;
} else if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $pword) === 0) {
$passwordErr = "Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit";
return $passwordErr;
}
return '';
}
/**
* It returns an error message, if any, in the gender
* #param type $gen
* #return string or null if not found
*/
function validateGender($gen) {
if (empty($gen)) {
$genderErr = "Gender is required";
return $genderErr;
} else if (($gen != "male") && ($gen != "female")) {
$genderErr = "Not a valid selection";
return $genderErr;
}
return '';
}
/**
* It returns an error message, if any, in the course
* #param type $cour
* #return string or null if not found
*/
function validateCourse($cour) {
if (empty($cour)) {
$courseErr = "Select atleast one";
return $courseErr;
} else if (array_values($cour) != ("PHP" && "HTML" && "CSS" && "Javascript")) {
$courseErr = "Not a valid selection";
return $courseErr;
}
return '';
}
/**
* It doesnot return an error message, but accepts any content
* #param type $comm
* #return null
*/
function validateComments($comm) {
if (empty($comm)) {
return '';
}
return '';
}
/**
* It removes any special characters in a string and inserts the validated user data into the database
* #param type $variables array
* #param type $con
* #param type $dbname
* #return boolean
*/
function cleanandinsert($variables, $con, $dbname) {
$firstname = mysqli_real_escape_string($con, $variables['firstname']); //The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.
$lastname = mysqli_real_escape_string($con, $variables['lastname']);
$username = mysqli_real_escape_string($con, $variables['username']);
$password = sha1($variables['password']);
$gender = mysqli_real_escape_string($con, $variables['gender']);
$string = implode(',', ($variables['course']));
$course = mysqli_real_escape_string($con, $string);
$comments = mysqli_real_escape_string($con, $variables['comments']);
$sql = "INSERT INTO $dbname.userdata (firstname,lastname,username,password,gender,course,comments)
VALUES ('$firstname','$lastname','$username','$password','$gender','$course','$comments')";
if (!mysqli_query($con, $sql)) {
return FALSE;
}
return TRUE;
}
/**
* It checks the checked checkboxes on the submission of the wrong data i.e it remembers the checked checkbox.
* #param type $course
* #return checked checkbox or null if a checkbox is not checked
*/
function getChecked($course){
if(!empty($_POST['course']) && in_array($course, $_POST["course"])){
return 'checked';
}
return '';
}
?>
You can use ladder if..else structure for your code
in if() you will put your condition and if the condition is false it will go to the error message and then you can put link of the main form, so that the user can go back...
There are many ways for doing this, but the easy way to do this is "Put your Whole form code in php file and just make one file, i am not sure but it should work, the error will be shown below the form for that first write your form code and after write your php script".:)

Categories