I have tried this code to add validation when the input is name and number. But, there is something wrong with this code. The validation for nama and telepon are always wrong. I use the form and validation in one page.Can you help me solve this problem
<?php
error_reporting(E_ALL);
class ValidateInfo
{
public $errors;
public $message;
public $data;
public $wrong;
public $wrongmessage;
public function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
{
$trimmed = trim($payload[$type]);
if(!empty($validate)) {
// Strip out all but numbers
if(in_array('digits',$validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
// not an integer!
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Telephon number must be in number';
} else {
$this->wrong[$type] = 0;
}
}
// Strip out letters
elseif(in_array('letters',$validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === true) {
// not an integer!
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Name must be in alphabet';
} else {
$this->wrong[$type] = 0;
}
}
// Re-assign data type to consolidate
$this->data[$type] = (!isset($this->data[$type]))? $trimmed:$this->data[$type];
// Check if data is an email
if(in_array('email',$validate)) {
if(filter_var($this->data[$type], FILTER_VALIDATE_EMAIL) === false){
$this->wrong[$type] = 1;
$this->wrongmessage[$type] = 'Tulis email seperti: yourname#email.com';
} else {
$this->wrong[$type] = 0;
}
}
// Strip out html tags
if(in_array('strip',$validate)) {
$this->data[$type] = strip_tags($this->data[$type]);
}
}
if(!isset($this->data[$type]))
$this->data[$type] = $trimmed;
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
}
}
// Creat instance of info processor
$info = new ValidateInfo();
// check if all form data are submited, else output error message
if(isset($_POST['submit'])) {
// Checks empty fields
$info->Check($_POST,'nama','Write your name',array('letters'));
$info->Check($_POST,'telepon','Write the phone number',array('digits'));
$info->Check($_POST,'email','Write the email',array('email'));
$info->Check($_POST,'judul','Write the title');
$info->Check($_POST,'konten','Write the content');
if(array_sum($info->errors) == 0 && array_sum($info->wrong) == 0) {
// path and name of the file
$filetxt = 'dataInJson.json';
// Assign stored data
$data = $info->data;
// path and name of the file
$filetxt = 'dataInJson.json';
// to store all form data
$arr_data = array();
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
// appends the array with new form data
$arr_data[] = $data;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "dataInJson.json"
// outputs error message if data cannot be saved
if(file_put_contents('dataInJson.json', $jsondata)) {
$info->errors['success'] = true; ?>
<script type="text/javascript">alert("Data has been submitted");</script>
<?php }
else {
$info->message['general']['put_file'] = 'Tidak dapat menyimpan data di "dataInJson.json"';
}
}
}
else
$info->message['general']['submit'] = 'Form fields not submited'; ?>
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="center">
<h1>Data Buku</h1>
<?php if(isset($info->errors['success'])) { ?>
<h2>Thank you!</h2>
<?php } else { ?>
<p><span class="error">* required field.</span></p>
<?php } ?>
<hr>
<form action="" method="post">
<?php if(isset($info->message['general'])) {
foreach($info->message['general'] as $_error) { ?>
<span class="error">* <?php echo $_error; ?></span><br>
<?php
}
} ?>
<h2>Informasi Pengarang</h2>
<div class="roadie">
<label for="nama">Nama:</label>
<input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value=" <?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
<?php
if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?>
<span class="error">* <?php echo $info->message['nama']; ?></span><?php
}
if(isset($info->wrong['nama']) && $info->wrong['nama'] == 1) { ?>
<span class="error">* <?php echo $info->wrongmessage['nama']; ?></span><br><?php
}?>
</div>
<div class="roadie">
<label for="telepon">Nomor Telepon:</label>
<input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
<?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span class="error">* <?php echo $info->message['telepon']; ?></span><?php }
if(isset($info->wrong['telepon']) && $info->wrong['telepon'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['telepon']; ?></span><br><?php } ?>
</div>
<div class="roadie">
<label for="email">e-Mail:</label>
<input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
<?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php }
if(isset($info->wrong['email']) && $info->wrong['email'] == 1) { ?><span class="error">* <?php echo $info->wrongmessage['email']; ?></span><br><?php }
?>
</div>
<div class="roadie">
<h2>Tulisan</h2>
<label for="judul">Judul:</label>
<input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
<?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
</div>
<div class="roadie">
<label for="konten">Konten:</label>
<textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) { echo strip_tags($info->data['konten']); } ?></textarea>
<?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
</div>
<input type="submit" id="submit" name = submit value="Create" />
<input type="reset" id="reset" value="Reset" />
</form>
I debugged your code, and the problem is:
When your program checks your nama field, it has option array('letters') for $validate.
elseif (in_array('letters', $validate)) {
if (filter_var($this->data[$type], FILTER_VALIDATE_INT) === false) {
So when you want to check letters, why do you use FILTER_VALIDATE_INT ?
The other problem is here:
if(!isset($this->data[$type])) {
$this->data[$type] = $trimmed;
}
$this->errors[$type] = (empty($this->data[$type]))? 1:0;
$this->message[$type] = $mess;
This block is at the end of your Check. So, when first run, you try to check an empty thing, and then when method finishes, the nama will be added to the $this->data. This is why your second Check call does not found the telpone. So move this block to the top of your method, and validate, is this exists. Validate formats only after this check.
Related
I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.
I am new to php and working on a hangman game. I have a home.php that takes you to the homepage and their is a login form that the user must submit a username and a password. If the username and password match with the one I have set, it will redirect to hangman.php. I want some advice if the way I have written the script is correct or not. Also, I am getting a 500 error after the user logs in. I don't know why. I will paste the code down below.
Update: I have added the code for hangman.php
home.php
<?php
// starting a new session
session_start();
if(isset($_POST['uname'], $_POST['psw'])){
$uname= "my_admin";
$psw = "password";
if($_POST['uname'] == $uname && $_POST['psw'] == $psw) {
$_SESSION["uname"] = "my_admin";
$_SESSION["psw"] = "password";
# array holds errors
$errors = array();
# validation starts here
if(empty($_POST['uname'])){
$errors['uname1'] = "Your name cannot be empty";
}
# check strlength
if(strlen($_POST['uname']) < 6){
$errors['uname2'] = "Must be longer than 6 characters";
}
# check username
if ($_POST['uname'] !== "my_admin"){
$errors['uname3'] = "You are not the admin";
}
if($_POST['uname'] == "my_admin" && $_POST['psw'] == "password"){
header('Location:hangman.php');
exit();
}else{
$errors['uname4'] = "Please try again";
}
if(empty($_POST['psw'])){
$errors['psw1'] = "Your password cannot be empty";
}
if(strlen($_POST['psw']) < 6){
$errors['psw2'] = "Must be longer than 6 characters";
}
if($_POST['psw'] !== "password"){
$errors['ps3'] = "AH AH AH thats not it";
}else{
header('Location:hangman.php');
exit();
}
if(count($errors) == 0){
# redirect to the game page
header('Location:hangman.php');
exit();
}
}
}
?>
form for my script to run against
<div class="container">
</p>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname">
<p>
<?php if(isset($errors['uname1']))
echo $errors['uname1']; ?>
</p>
<p>
<?php if(isset($errors['uname2']))
echo $errors['uname2']; ?>
</p>
<p>
<?php if(isset($errors['uname3']))
echo $errors['uname3']; ?>
</p>
<p>
<?php if(isset($errors['uname4']))
echo $errors['uname4']; ?>
</p>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw">
<p>
<?php if(isset($errors['psw1'])) echo $errors['psw1']; ?>
</p>
<p>
<?php if(isset($errors['psw2'])) echo $errors['psw2']; ?>
</p>
<?php if(isset($errors['psw3'])) echo $errors['psw3']; ?>
</p>
<button name="check" type="submit" value="submit">Login</button>
</div>
</form>
hangman.php
<?php
require_once 'hangedman.php';
$words = array('VIETNAM', 'PEOPLE', 'PYTHON');
$numwords = 0;
function printPage($image, $guesstemplate, $which, $guessed, $wrong) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<link rel="stylesheet" type="text/css" href="home.css">
</head>
</html>
<body>
<h1 style='color: red'>Hangman Game</h1>
<br />
<pre style='color: red'>$image</pre>
<br />
<p style='color:red'><strong>Word to guess: $guesstemplate</strong></p>
<p style='color:red'>Letters used in guesses so far: $guessed</p>
<form method="post" action="$script">
<input type="hidden" name="wrong" value="$wrong" />
<input type="hidden" name="lettersguessed" value="$guessed" />
<input type="hidden" name="word" value="$which" />
<fieldset>
<legend style='color: red'>Your next guess</legend>
<input type="text" name="letter" autofocus />
<input type="submit" value="Guess" />
</fieldset>
</form>
</body>
ENDPAGE;
}
function loadWords() {
global $words;
global $numwords;
$input = fopen("./words.txt", "r");
while (true) {
$str = fgets($input);
if (!$str) break;
$words[] = rtrim($str);
$numwords++;
}
fclose($input);
}
function startGame() {
global $words;
global $numwords;
global $hang;
$which = rand(0, $numwords - 1);
$word = $words[$which];
$len = strlen($word);
$guesstemplate = str_repeat('_ ', $len);
$script = $_SERVER["PHP_SELF"];
printPage($hang[0], $guesstemplate, $which, "", 0);
}
function killPlayer($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You lost!</h1>
<p>The word you were trying to guess was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function congratulateWinner($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You win!</h1>
<p>Congratulations! You guessed that the word was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function matchLetters($word, $guessedLetters) {
$len = strlen($word);
$guesstemplate = str_repeat("_ ", $len);
for ($i = 0; $i < $len; $i++) {
$ch = $word[$i];
if (strstr($guessedLetters, $ch)) {
$pos = 2 * $i;
$guesstemplate[$pos] = $ch;
}
}
return $guesstemplate;
}
function handleGuess() {
global $words;
global $hang;
$which = $_POST["word"];
$word = $words[$which];
$wrong = $_POST["wrong"];
$lettersguessed = $_POST["lettersguessed"];
$guess = $_POST["letter"];
$letter = strtoupper($guess[0]);
if(!strstr($word, $letter)) {
$wrong++;
}
$lettersguessed = $lettersguessed . $letter;
$guesstemplate = matchLetters($word, $lettersguessed);
if (!strstr($guesstemplate, "_")) {
congratulateWinner($word);
} else if ($wrong >= 6) {
killPlayer($word);
} else {
printPage($hang[$wrong], $guesstemplate, $which, $lettersguessed, $wrong);
}
}
//header("Content-type: text/plain");
loadWords();
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
handleGuess();
} else {
startGame();
}
?>
If I echo $codeee outside of the if loop, the value shows, but the value does not exist inside the loop which causes the UPDATE query to fail. How can I use the variable inside the loop?
PHP Code
require('connect.php');
$codeee = htmlspecialchars($_GET["recov"]);
echo $codeee;
$paso = $confpaso = "";
$pasoErr = $confpasoErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["paso"])) {
$pasoErr = "Password is required";
} else {
$paso = md5(test_inputing($_POST["paso"]));
}
$confpaso = md5(test_inputing($_POST["confpaso"]));
if ($confpaso != $paso) {
$confpasoErr = "Passwords do not match";
}
$emailing = test_inputing($_POST["emailing"]);
if ($pasoErr == $confpasoErr && $confpasoErr == "") {
$changepaso = "UPDATE users SET password='$paso' WHERE forgotcode = '$codeee'";
if ($conn->query($changepaso) === TRUE) {
$tellthem = "Your password was changed";
} else {
$tellthem = "Something Happened, the password was not changed";
}
}
}
HTML CODE
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?> method="post">
<div class="register-top-grid">
<h3>FILL OUT YOUR INFORMATION TO CHANGE YOUR PASSWORD</h3>
<div>
<span>Email<label>*</label></span>
<input type="text" name="emailing" >
</div>
<div>
<span>Password<label>*</label><p style="color:red"><?php echo $pasoErr ?></p></span>
<input type="password" name="paso" >
</div>
<div>
<span>Confirm Password<label>*</label><p style="color:red"><?php echo $confpasoErr ?></p></span>
<input type="password" name="confpaso" >
</div>
</div></br></br>
<input type="submit" value="submit">
<p><?php echo $tellthem ?></p>
</form>
I've got everything worked out for my Support Ticket website, except my newticket form isn't posting the values to the database. Here is what I have:
<?php
ob_start();
session_start();
include 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
$error = false;
}
if ( isset($_POST['btn-cancel']) ) {
header("Location: home.php");
exit;
}
if ( isset($_POST['btn-signup']) ) {
// get form results
$text = $_POST['description'];
$text = strip_tags($text);
$userid = $_POST['user'];
$problem = $_POST['problem'];
$room = $_POST['room'];
$status = 1;
$datetime = date('Y-m-d G:i:s');
// description validation
if (empty($text)) {
$error = true;
$textError = "Please describe the problem.";
} else if (strlen($text) > 200) {
$error = true;
$textError = "Description must be less than 200 characters in length.";
}
// dropdown validation
if ($problem < 1){
$error = true;
$problemError = "Please choose a category and problem.";
} else if ($room < 1) {
$error = true;
$roomError = "Please choose a building and a room number.";
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO job (User_UserID,Problem_ProblemID,Status_StatusID,Room_RoomID,Description,Date_Time) VALUES({$userid},{$problem},{$status},{$room},'{$text}',{$dateTime})";
echo '$query';
$res = mysqli_query($conn,$query);
if ($res) {
$errTyp = "success";
$errMSG = "Successfully submited ticket";
unset($text);
unset($problem);
unset($room);
unset($datetime);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later.";
}
}
}
}
?>
HTML:
<!DOCTYPE html>
<html>
<head>
<SCRIPT language=JavaScript>
<!--
//function reload(form)
{
//var val=form.type.options[form.type.options.selectedIndex].value;
//self.location='newticket.php?type=' + val ;
}
//function reload2(form)
{
//var val=form.building.options[form.building.options.selectedIndex].value;
//self.location='newticket.php?building=' + val ;
}
function disableselect()
{
<?Php
if(isset($type) and strlen($type) > 0){
echo "document.f1.problem.disabled = false;";}
else{echo "document.f1.problem.disabled = true;";}
if(isset($building) and strlen($type) > 0){
echo "document.f1.room.disabled = false;";}
else{echo "document.f1.room.disabled = true;";}
?>
}
//-->
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dog Tracks - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body onload=disableselect();>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Create New Ticket</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group">
<?php
//Getting the data for first list box
$quer2="SELECT problem_typeid,problem_type FROM problem_type ORDER BY problem_type";
echo "<select name='type' onchange=\"reload(this.form)\"><option value=''>Pick problem category</option>";
//while($result2 = mysql_fetch_array($quer2)) {
foreach (mysqli_query($conn,$quer2) as $result2) {
if($result2['problem_typeid']==$type){echo "<option selected value='$result2[problem_typeid]'>$result2[problem_type]</option>"."<BR>";}
else{echo "<option value='$result2[problem_typeid]'>$result2[problem_type]</option>";}
}
echo "</select>";
$type=$_GET['type'];
// for second drop down list
if(isset($type) and strlen($type) > 0){
$quer="SELECT problemid,problem FROM problem WHERE
Problem_Type_Problem_TypeID={$type} order by problem";
}else {
$quer="SELECT problemid,problem FROM problem order by problem";
}
echo "<select name='problem'><option value=''>What is the problem?</option>";
//while($result = mysql_fetch_array($quer)) {
foreach (mysqli_query($conn,$quer) as $result) {
echo "<option value='$result[problemid]'>$result[problem]</option>";
}
echo "</select>";
//// Add your other form fields as needed here/////
?>
</div>
<span class="text-danger"><?php echo $problemError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<?php
#$building=$_GET['building'];
//Getting the data for first list box
$quer3="SELECT buildingid,building FROM building ORDER BY building";
// for second drop down list
if(isset($building) and strlen($building) > 0){
$quer4="SELECT roomid,roomNum FROM room WHERE
building_buildingID=$building order by roomNum";
}else {
$quer4="SELECT roomid,roomNum FROM room order by roomNum";
}
echo "<select name='building' onchange=\"reload2(this.form)\"><option value=''>In which building?</option>";
//while($result2 = mysql_fetch_array($quer3)) {
foreach (mysqli_query($conn,$quer3) as $result3) {
if($result3['buildingid']==#$building){echo "<option selected value='$result3[buildingid]'>$result3[building]</option>"."<BR>";}
else{echo "<option value='$result3[buildingid]'>$result3[building]</option>";}
}
echo "</select>";
echo "<select name='room'><option value=''>In what room?</option>";
//while($result = mysql_fetch_array($quer)) {
foreach (mysqli_query($conn,$quer4) as $result4) {
echo "<option value='$result4[roomid]'>$result4[roomNum]</option>";
}
echo "</select>";
//// Add your other form fields as needed here/////
?>
</div>
<span class="text-danger"><?php echo $roomError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<textarea cols='72' id='description' rows='6' placeholder="Description">
Please describe the problem here. </textarea>
</div>
<span class="text-danger"><?php echo $textError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-submit">Submit</button>
<button type="submit" class="btn btn-block btn-primary" name="btn-cancel">Cancel</button>
</div>
<div class="form-group">
<hr />
</div>
</form>
</div>
</div>
</body>
</html>
<?php
mysqli_close($conn);
ob_end_flush();
?>
First
if ($problem < 1){
$error = true;
$problemError = "Please choose a category and problem.";
} else if ($room < 1) {
$error = true;
$roomError = "Please choose a building and a room number.";
Oops, you don't close that else if, so your INSERT is always skipped.
The next problem
One part of the code that looks dodgy are these lines:
$datetime = date('Y-m-d G:i:s');
//...
$query = "INSERT INTO job (User_UserID,Problem_ProblemID,Status_StatusID,Room_RoomID,Description,Date_Time)
VALUES({$userid},{$problem},{$status},{$room},'{$text}',{$dateTime})";
^^^^^^^^^^^
Your $dateTime will be something like 2016-12-09 11:43:42, so the SQL statement will be:
INSERT INTO job (...) VALUES(..., 'This is my text', 2016-12-09 11:43:42)
This is a syntax error. Note that your $text field has quotes around it to keep it as a single element, but your date does not. Using '{$dateTime}' will fix this problem, although there is no guarantee that there is no other issue...
Currently I am sending error messages and storing the value of my input fields in sessions.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductPrice']; unset($_SESSION['msgProductPrice']); ?></label>
<input type="text" name="product_price" value="<?php echo $_SESSION['val_ProductPrice']; unset($_SESSION['val_ProductPrice']); ?>" />
PHP
$Price = $_POST['product_price'];
$errorcount = 0;
if(empty($Price) === true){
$PriceErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductPrice'] = $Price;
$_SESSION['msgProductPrice'] = $PriceErrormsg;
}
This works perfectly with one of a kind input field. If I try with multiple input fields with the same name, it doesn't work.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
This is where I'm unsure on how to validate all the input fields, how to keep the value in each input field when you hit submit and how to send an errormsg about each field?
PHP
$Amount= $_POST['product_amount'];
$errorcount = 0;
if(empty($Amount) === true){
$AmountErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrormsg;
}
If I understand your problem, multiple product amounts are being submitted, and you want to validate each one individually and display the error message next to the appropriate textbox?
Because you are receiving an array of values, you need to create a corresponding array of error messages.
It's a while since I've done any PHP, so this might not be 100% correct, but I think you need something along these lines...
$AmountErrorMessage = Array();
foreach ($Amount as $key => $value) {
if (empty($value)) {
$AmountErrorMessage[$key] = 'empty';
}
}
if ($AmountErrorMessage->count() > 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrorMessage;
}
You would then also need to iterate through the array in order to generate the HTML for your form, creating a label and input box for each value submitted.
This code help you to do it as per your wish..
<?php
session_start();
?>
<html>
<head>
<title></title>
<style>
.errormsg{
color:red;
}
</style>
</head>
<body>
<?php
if(isset($_POST['product_amount']))
{
$errorcount = 0;
for($i=0;$i<count($_POST['product_amount']);$i++){
$Amount[$i] = $_POST['product_amount'][$i];
if(empty($Amount[$i]) === true){
$_SESSION['msgProductAmount'][$i] = "empty";
$errorcount++;
}
else
$_SESSION['val_ProductAmount'][$i] = $Amount[$i];
}
if($errorcount === 0) {
unset($_SESSION['msgProductAmount']);
echo "success";
}
}
?>
<form action="" method="POST">
<?php
$cnt = 10;
for($i=0;$i<$cnt;$i++){
?>
<input type="text" name="product_amount[<?=$i?>]" value="<?php echo isset($_SESSION['val_ProductAmount'][$i]) ? $_SESSION['val_ProductAmount'][$i] : '';?>" />
<label class="errormsg"><?php echo $res = isset($_SESSION['msgProductAmount'][$i]) ? $_SESSION['msgProductAmount'][$i] : '' ; ?></label>
<br/>
<?php
}
?>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
unset($_SESSION['msgProductAmount'],$_SESSION['val_ProductAmount']);
?>