select option dropdown hidden input validation - php

In the below code: i have a select option dropdown(Employed,UmEmployed) If i select Option Employed it shows some input field(Current Designation, Current CTC) if i submit data without inserting anything it show validation: current designation is required.
If i select another option from dropdown that is unemployed it should redirect to another page directly but its not going to success.php (unemployed) that one is also validating.
<html>
<head>
<style>
#employer
{
display:none;
}
.error
{
color:#F00;
}
</style>
<?php
$currentdes="";
$currentdesErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["desig"]))
{
$currentdesErr="* Current Designation is Required";
$valid=false;
echo "<style>#employer{display:block;}</style>";
}
else
{
$currentdes=test_input($_POST["desig"]);
}
//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "currentsta" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "1") echo "selected"; ?>>Employed</option>
<option value = "2" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "2") echo "selected"; ?>>UnEmployed</option>
</select>
</p>
<div id="employer">
Current Designation: <label><input type="text" name="desig" size="50" /></label>
<span class="error"><?php echo $currentdesErr?></span>
<br>
Current CTC: <label><input type="text" size="50" /></label><br>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
$('#employer').hide();
}
});
</script>
<!--currentstatus Ends here-->
<!--Submit Button-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>

The desig input field will be empty for unemployed option as it is not being filled. Hence you should consider both the conditions. Also don't include database.php in the if block . Instead inside the success.php
<html>
<head>
<style>
#employer
{
display:none;
}
.error
{
color:#F00;
}
</style>
<?php
$currentdes="";
$currentdesErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["desig"]) && $_POST["currentsta"]==1)
{
$currentdesErr="* Current Designation is Required";
$valid=false;
echo "<style>#employer{display:block;}</style>";
}
else
{
$currentdes=test_input($_POST["desig"]);
}
//if valid then redirect
if($valid){
//include 'database.php';
header('Location:success.php');
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "currentsta" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "1") echo "selected"; ?>>Employed</option>
<option value = "2" <?php if(isset($_POST["currentsta"]) && $_POST["currentsta"] == "2") echo "selected"; ?>>UnEmployed</option>
</select>
</p>
<div id="employer">
Current Designation: <label><input type="text" name="desig" size="50" /></label>
<span class="error"><?php echo $currentdesErr?></span>
<br>
Current CTC: <label><input type="text" size="50" /></label><br>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
$('#employer').hide();
}
});
</script>
<!--currentstatus Ends here-->
<!--Submit Button-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>

If on selection of unemployed option, you want to redirect to another page, then redirect it using JavaScript.
In the script at the end of the page, the modification would be -
$('p select[name=currentsta]').change(function(e){
if ($('p select[name=currentsta]').val() == '1'){
$('#employer').show();
}else{
//$('#employer').hide();
//This redirects to next page on selecting the option.
window.location.href= "success.php";
}
});

Related

Simple server-side validation using php

i have a problem with the validation my input and select fields.
If the inputs are empty and click on submit the warning "this field is required" appears.
But when i fill the ClientID input and the selection box is empty the validation will fail. Or invers, when the select box is selected and the input is empty.
here my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $katalogErr = $selectKatalog = "";
$kdn = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["kdn"])) {
$nameErr = "This field is required";
} else {
$kdn = test_input($_POST["kdn"]);
// check if kdn only contains letters, numbers and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/", $kdn)) {
$nameErr = "Only letters, numbers and white space allowed";
}
}
if($_POST["selectKatalog"] == 'default'){
$katalogErr = "This field is required";
}
else {
$selectKatalog = $_POST["selectKatalog"];
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Order a Catalog</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
ClientID: <input type="text" name="kdn">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Catalog: <select name="selectKatalog">
<option value="default">Bitte wählen:</option>
<option value="Catalog1">Catalog1</option>
<option value="Catalog2">Catalog2</option>
<option value="Catalog3">Catalog3</option>
</select>
<span class="error">* <?php echo $katalogErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $kdn;
echo "<br>";
echo $selectKatalog;
?>
</body>
</html>

if ($_POST) always returns false

I'm having some trouble with a Form. It contains an input type File for uploading an image, and a select tag to choose where to put this image.
Code goes like this:
<?php
require_once("functions.php");
if(isset($_COOKIE['user']))
{
$username= checkcookie($_COOKIE['user']);
}
if (isset($_SESSION['user'])) {
if ($_POST) {
$errors = array();
$errors = SomeValidation();
if (empty($errors )) {
UpdateImages();
exit;
}else {
Header ("location: somefile.php?error=There was an error");
exit;
}
}else{
var_dump("error");
} ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<?php if(isset($_GET['error'])) {?>
<div class="alert alert-danger" role="alert">
<ul>
<li><?php echo $_GET['error'] ?></li>
</ul>
</div>
<?php } ?>
<div class="cbp-mc-column">
<label>Choose new Image</label>
<select id="code" name="code">
<option value="1" >First</option>
<option value="2" >Second</option>
<option value="3" >Third</option>
</select>
<br/>
<input type="file" name="newimage" value="" />
<br>
<input type="submit" name="update" value="Update">
<br>
</div>
</form>
<!-- Bootstrap Core JavaScript -->
<script src="../js/bootstrap.min.js"></script>
</body>
</html>
<?php }else
{
header('location: panel.php');
}
?>
I'm always getting False for if($_POST), and also when I submit the form.
Any idea why?
EDIT: I forgot to mention, I'm sending the select value via post, so I can choose which file upload, and It is always empty.
to upload image or any other file you need to check the $_FILES array not post,
this question could be helpfull
How do you loop through $_FILES array?
It is better to check inputs instead of request method.. so use
if (!empty($_POST["update"])) {
....
}
First, you need to check if the submit button was clicked :isset($_POST['update'])
Next, check if a file has been selected: isset($_FILES['newimage']['tmp_name'])
if (isset($_POST['update'])) {
if (isset($_FILES['newimage']['tmp_name'])) {
$errors = array();
$errors = SomeValidation();
if (empty($errors )) {
UpdateImages();
exit;
} else {
Header ("location: somefile.php?error=There was an error");
exit;
}
} else {
echo "No file selected.";
}
} else {
echo "Not a POST request.";
}

Customized validation messages not working?

Am trying to add custom validation messages to this form, but cannot figure it out for the life of me..
Any help/advice is appreciated...thank you.
I have tried a few tutorials, but nothing seems to be clicking for me, I am sure its something simple, but I just cant seem to figure it out.
Thanks
FORM FOR THE VALIDATION:
<?php
if (isset($_POST['insert'])) {
require_once('connection.php');
$OK = false;
$sql = 'INSERT INTO students (studentTitle, studentFirstName, studentLastName)
VALUES(:studentTitle, :studentFirstName, :studentLastName)';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':studentTitle', $_POST['studentTitle'], PDO::PARAM_STR);
$stmt->bindParam(':studentFirstName', $_POST['studentFirstName'], PDO::PARAM_STR);
$stmt->bindParam(':studentLastName', $_POST['studentLastName'], PDO::PARAM_STR);
$stmt->execute();
$OK = $stmt->rowCount();
if ($OK) {
header('Location: http://localhost/mysqlquiz/student.php');
exit;
} else {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Add Student Details</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="header">New student details</h1>
<p>Student Listing </p>
<?php
if (isset($error)) {
echo "<p class='warning'>Error: $error</p>";
}
?>
<?php
// define variables and set to empty values
$studentTitleErr = $studentFirstNameErr = $studentLastNameErr = "";
$studentTitle = $studentFirstName = $studentLastName = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["studentTitle"])) {
$studentTitleErr = "A title is required";
} else {
$studentTitle = test_input($_POST["studentTitle"]);
}
if (empty($_POST["studentFirstName"])) {
$studentFirstNameErr = "First name is required";
} else {
$studentFirstName = test_input($_POST["studentFirstName"]);
}
if (empty($_POST["studentLastName"])) {
$studentLastNameErr = "Last name is required";
} else {
$studentLastName = test_input($_POST["studentLastName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p>
<label for="studentTitle">Title:</label>
<select name="studentTitle" id="studentTitle" ><span class="error">* <?php echo $studentTitleErr;?></span>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss.</option>
</select>
</p>
<p>
<label for="studentFirstName">First Name:</label>
<input type="text" name="studentFirstName" id="studentFirstName" ><span class="error">* <?php echo $studentFirstNameErr;?></span>
</p>
<p>
<label for="studentLastName">Last Name:</label>
<input type="text" name="studentLastName" id="studentLastName" ><span class="error">* <?php echo $studentLastNameErr;?></span>
</p>
<p>
<input type="submit" name="insert" value="Add Details" id="insert">
<input type="reset" name="clear" value="Clear" id="clear">
<input name="studentID" type="hidden" value="<?php echo $studentID; ?>">
</p>
</form>
</body>
</html>
I have updated your code. you should check the validation first then insert.
<?php
// define variables and set to empty values
$studentTitleErr = $studentFirstNameErr = $studentLastNameErr = "";
$studentTitle = $studentFirstName = $studentLastName = "";
if (isset($_POST['insert'])) {
require_once('connection.php');
$error = $OK = false;
if (empty($_POST["studentTitle"])) {
$studentTitleErr = "A title is required";
$error = true;
} else {
$studentTitle = test_input($_POST["studentTitle"]);
}
if (empty($_POST["studentFirstName"])) {
$studentFirstNameErr = "First name is required";
$error = true;
} else {
$studentFirstName = test_input($_POST["studentFirstName"]);
}
if (empty($_POST["studentLastName"])) {
$studentLastNameErr = "Last name is required";
$error = true;
} else {
$studentLastName = test_input($_POST["studentLastName"]);
}
if($error == false)
{
$sql = 'INSERT INTO students (studentTitle, studentFirstName, studentLastName)
VALUES(:studentTitle, :studentFirstName, :studentLastName)';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':studentTitle', $_POST['studentTitle'], PDO::PARAM_STR);
$stmt->bindParam(':studentFirstName', $_POST['studentFirstName'], PDO::PARAM_STR);
$stmt->bindParam(':studentLastName', $_POST['studentLastName'], PDO::PARAM_STR);
$stmt->execute();
$OK = $stmt->rowCount();
if ($OK) {
header('Location: http://localhost/mysqlquiz/student.php');
exit;
} else {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Add Student Details</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="header">New student details</h1>
<p>Student Listing </p>
<?php
if (isset($error)) {
echo "<p class='warning'>Error: $error</p>";
}
?>
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<p>
<label for="studentTitle">Title:</label>
<select name="studentTitle" id="studentTitle" ><span class="error">* <?php echo $studentTitleErr;?></span>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss.</option>
</select>
</p>
<p>
<label for="studentFirstName">First Name:</label>
<input type="text" name="studentFirstName" id="studentFirstName" ><span class="error">* <?php echo $studentFirstNameErr;?></span>
</p>
<p>
<label for="studentLastName">Last Name:</label>
<input type="text" name="studentLastName" id="studentLastName" ><span class="error">* <?php echo $studentLastNameErr;?></span>
</p>
<p>
<input type="submit" name="insert" value="Add Details" id="insert">
<input type="reset" name="clear" value="Clear" id="clear">
<input name="studentID" type="hidden" value="<?php echo $studentID; ?>">
</p>
</form>
</body>
</html>
Because your DB insert operation runs first and has no checks for required field data in order to run or not. So, it runs, and on success it redirects and exits:
header('Location: http://localhost/mysqlquiz/student.php');
exit;
Which clears POST and your required field logic never gets run.

Form validation to see if the email already excists in the MySQL database

At the moment I have a form (PHP & jQuery) with validations. I want to add a validation to check if the email address of a new user is already in the MySQL database or not.
At the moment there are 3 (IF) validations already for the name and email in jQuery:
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
I would like to have a 4th one to check if the email address is already in the MySQL database.
The complete PHP file with jQuery:
<?php
include 'db_connection.php';
if(isset($_POST['finish'])){
$name = '"'.$dbConnection->real_escape_string($_POST['name']).'"';
$email = '"'.$dbConnection->real_escape_string($_POST['email']).'"';
$password = '"'.password_hash($dbConnection->real_escape_string($_POST['password']), PASSWORD_DEFAULT).'"';
$gender = '"'.$dbConnection->real_escape_string($_POST['gender']).'"';
$sqlInsertUser = $dbConnection->query("INSERT INTO users (name, password, email, gender) VALUES($name, $password, $email, $gender)");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/text.css" />
<link rel="stylesheet" href="css/960.css" />
<link rel="stylesheet" href="css/demo.css" />
<script src="scripts/jquery-1.10.2.js"></script>
<style>
CSS CODE
</style>
<script>
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
}
if($("#password-field").css('display') != 'none') {
if(!($("#user-password").val())) {
output = false;
$("#password-error").html("Password required!");
}
if(!($("#confirm-password").val())) {
output = false;
$("#confirm-password-error").html("Confirm password required!");
}
if($("#user-password").val() != $("#confirm-password").val()) {
output = false;
$("#confirm-password-error").html("Password not matched!");
}
}
return output;
}
$(document).ready(function() {
$("#next").click(function(){
var output = validate();
if(output) {
var current = $(".active");
var next = $(".active").next("li");
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("#back").show();
$("#finish").hide();
$(".active").removeClass("active");
next.addClass("active");
if($(".active").attr("id") == $("li").last().attr("id")) {
$("#next").hide();
$("#finish").show();
}
}
}
});
$("#back").click(function(){
var current = $(".active");
var prev = $(".active").prev("li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("#next").show();
$("#finish").hide();
$(".active").removeClass("active");
prev.addClass("active");
if($(".active").attr("id") == $("li").first().attr("id")) {
$("#back").hide();
}
}
});
});
</script>
</head>
<body>
<div class="container_12">
<div class="grid_8">
<p>
TEXT<br>TEXT<br>TEXT<br>TEXT<br>TEXT
</p>
</div>
<div class="grid_4">
<p>Register new FC Magnate</p>
<div class="message"><?php if(isset($message)) echo $message; ?></div>
<ul id="signup-step">
<li id="personal" class="active">Personal Detail</li>
<li id="password">Password</li>
<li id="general">General</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post">
<div id="personal-field">
<label>Name</label><span id="name-error" class="signup-error"></span>
<div><input type="text" name="name" id="name" class="demoInputBox"/></div>
<label>Email</label><span id="email-error" class="signup-error"></span>
<div><input type="text" name="email" id="email" class="demoInputBox" /></div>
</div>
<div id="password-field" style="display:none;">
<label>Enter Password</label><span id="password-error" class="signup-error"></span>
<div><input type="password" name="password" id="user-password" class="demoInputBox" /></div>
<label>Re-enter Password</label><span id="confirm-password-error" class="signup-error"></span>
<div><input type="password" name="confirm-password" id="confirm-password" class="demoInputBox" /></div>
</div>
<div id="general-field" style="display:none;">
<label>Gender</label>
<div>
<select name="gender" id="gender" class="demoInputBox">
<option value="female">Female</option>
<option value="male">Male</option>
</select></div>
</div>
<div>
<input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
<input class="btnAction" type="button" name="next" id="next" value="Next" >
<input class="btnAction" type="submit" name="finish" id="finish" value="Finish" style="display:none;">
</div>
</form>
</div>
The "db_connection.php" file:
<?php
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', '****');
define('_DATABASE_NAME', '****');
$dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
if ($dbConnection->connect_error) {
trigger_error('Connection Failed: ' . $dbConnection->connect_error, E_USER_ERROR);
}
?>
I tried to create this validation from other examples that were given here on the website. But, no success. Please, it would be great if somebody could help me a little further.
UPDATE: With the help of Suyog I changed the files. But, it doesn't seem to work yet. Here are the files that I use at the moment: fcmagnate.com/files.zip
The form works till the moment the validation of the email address in the database starts, than it stops.
You will have to make use of JQuery AJAX for this.
Write a function in AJAX to send email to php gage where we will check the existance of email.
<script>
function checkEmail(eMail)
{
$.ajax({
url: 'check_email.php',
data: {emailId: eMail},
type: 'post',
success: function (data) {
if(data == '1')
return false;
else
return true;
}
});
}
</script>
Then you can call this function
<script>
function validate()
{
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none')
{
if(!($("#name").val()))
{
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val()))
{
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#email-error").html("Invalid Email!");
output = false;
}
if(!checkEmail($("#email").val()))
{
$("#email-error").html("Email already exist!");
output = false;
}
}
}
</script>
Youe check_email.php file will contain the code as follows
<?php
include 'db_connection.php';
if(isset($_POST['emailId']))
{
$email = '"'.$dbConnection->real_escape_string($_POST['emailId']).'"';
$sqlCheckEmail = $dbConnection->query("SELECT user_id FROM users WHERE LOWER(email) like LOWER('%".$email."%')");
if($sqlCheckEmail->num_rows == 1)
echo '1';
else
echo '0';
}
?>
Use Ajax jQuery.ajax on client side to communicate with server side reusing your php code mentioned.

How to insert data into database only when input are not empty?

I came up with a problem which made me crazy as I am new to PHP. The problem is: the below timetable submission form works good on Chrome (every time I left the email unfilled, the submission cannot be processed). However, when using on safari, you can always submit blank form into the database.
Here is the html form.
<script type="text/javascript" src="/membership/my-form/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="/membership/my-form/js/main.js"></script>
<form class="mf-form floating-labels" method="post" action="timetablesubmit.php">
<div>
<h1 style="text-align:center">Availability form</h1>
</div>
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
</p>
<div>
<input name="location1" value="A" type="hidden">
<input name="location2" value="B" type="hidden">
</div>
<div class="AMY box">You work in A.</div>
<div class="TOM box">You work in B.</div>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Amy"){
$(".box").hide();
$(".AMY").show();
}
if($(this).attr("value")=="Tom"){
$(".box").hide();
$(".TOM").show();
}
});
}).change();
});
</script>
<style type="text/css">
.box{
padding: 10px;
display: none;
margin-top: 20px;
border: 1px solid #000;
font-size:1.6em;
text-align:center;
background-color: #f1f1f1;
}
</style>
Here is the timetablesubmit.php:
<?php
header("content-type:text/html;charset=utf-8");
session_start();
$timesubmit=date('Y-m-d H:i:s');
$staff=$_POST['timetable-staff'];
$email=$_POST['timetable-email'];
$con=mysql_connect("localhost","database","password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<? require 'header.php'; ?>
<div class="tk-reg">
<p>Thak you <?php echo $_POST['timetable-staff']; ?><p>
<p> Time availability submitted successfully.<p>
Your email address is: <?php echo $_POST["timetable-email"]; ?>
</div>
<div class="tk-regfollow">
<ul style="text-align:center">
Back to home page.
</ul>
</div>
</html>
Then I searched the Internet and changed to below, still not working on Safari (the alert appears, however data still been insert into database.
<?php
require 'header.php';
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["timetable-staff"])) {
$nameErr = "Please select a staff.";
} else {
$staff = test_input($_POST["timetable-staff"]);
}
if (empty($_POST["timetable-email"])) {
$emailErr = "Email address is required";
} else {
$email = test_input($_POST["timetable-email"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysql_connect("localhost","database_name","database_password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database_name", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<style>
.error {color: #FF0000;}
</style>
<h1 style="text-align:center">Availability form for
<?php
$d=strtotime("+1 Months");
echo date("M", $d) . " 2015 <br>";
?>
</h1>
<form class="mf-form floating-labels" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
<span class="error">* <?php echo $nameErr;?></span>
</p>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</html>
I hope someone could help me pointing out my mistakes. Thank you.
======================================================================
I tried a lot of ways to figure this out, however still have either 'this' or 'that' problems. I finally use a method that actually work, but I do not know whether it is not recommended.
Here is the code I modified in timetablesubmit.php
(my flow is: timetable.php ==>timetablesubmit.php==>welcome.php)
$email = trim($_POST['timetable-email']);
if($email !='' and $email !=null) {
$sql1;
}
else {
echo '<html><head>
<link rel="stylesheet" type="text/css" href="/membership/style.css"/>
<head>
<div class="check-error-message">
<p>Error: Email address is required.</p><br>
Return
</div>';
exit;
};
You can check with condition before insert operation
if($nameErr =="" && $emailErr == "")
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}
you can have one condition here to avoid empty fill
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
here keep this condition like this
if($staff!='' && $email!='')
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}
Html 5 "required" will not work in safari.
This line is the problem <input class="email" type="email" name="timetable-email" id="mf-email" required>
Write jquery/javascript validation to check the required field.
Hope its help you.
As they said, not all browsers accept the attribute required because it's new.
On PHP, server side, you can validate too if there's something filled with:
$var = trim($_POST['var']);
if(!is_empty($var)) {
//do mysqli function
}
else {
//show error
}
trim will remove blank spaces at start and end of the value given.
is_empty will be almost like $var == ""

Categories