PHP session array and input validation - php

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']);
?>

Related

PHP form with multiple steps and validation

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.

PHP - Can not access the checkbox value that has been checked

For my databases project I am doing this form where a user can select the information he wants and it will be displayed on a html page. For the time being I am implementing only the checkboxes where I am encountering a problem.
The problem is that when I check the checkboxes (for my current implementation I am only interested in the case where the user checks "Location"+ "Pipe-Type" + "Amount") in my action page "fe_page2.php", the if condition that checks to see if the checkboxes are checked is never being reached instead it always goes to the else condition. The code is provided below.
This is my basic html page:
<html>
<head>
<title>Flow Element</title>
</head>
<body>
<h1 style="margin-left: 450px">Retrieve Flow Element Information</h1>
<hr>
<form action="fe_page2.php" method="post">
All Times:
<input type="checkbox" name="alltimes" onchange="changeFields()"><br><br>
Start Date:
<input type="date" name="startdate" id="startdate">
Start Time:
<input type="time" name="starttime" id="starttime"><br><br>
Same Time:
<input type="checkbox" name="sametime" id = "sametime" onchange="sameFields()"><br><br>
End Date:
<input type="date" name="enddate" id="enddate">
End Time:
<input type="time" name="endtime" id="endtime"><br><br>
<h3> Select fields of output</h3>
<hr>
Pipe Key: <input type="text" name="pipepirmary" id="pipekey"><br>
<input type="checkbox" name="pipelocation" id="pipeLocation" value="value1" >
Location<br>
<input type="checkbox" name="Pipe-Type" id="pipetype" value="value2">
Pipe-Type<br>
<input type="checkbox" name="amount" id="amount" value="value3">
Amount<br><br>
Flow Element:<input type="text" name="fepirmarykey" id="fekey"/><br>
<input type="checkbox" name="flow" id="flo">
Flow<br>
<input type="checkbox" name="temperature" id="temp">
Temperature<br>
<input type="checkbox" name="pressure" id="pres">
Pressure<br><br>
<input type="submit">
</form>
<script>
function changeFields() {
if(document.getElementById("startdate").disabled == false){
document.getElementById("startdate").disabled = true;
document.getElementById("starttime").disabled = true;
document.getElementById("enddate").disabled = true;
document.getElementById("endtime").disabled = true;
document.getElementById("sametime").disabled = true;
if(document.getElementById("sametime").checked = true){
document.getElementById("sametime").checked = false;
}
document.getElementById("startdate").value = null;
document.getElementById("starttime").value = null;
document.getElementById("enddate").value = null;
document.getElementById("endtime").value = null;
}
else{
document.getElementById("startdate").disabled = false;
document.getElementById("starttime").disabled = false;
document.getElementById("enddate").disabled = false;
document.getElementById("endtime").disabled = false;
document.getElementById("sametime").disabled = false;
}
}
function sameFields() {
if(document.getElementById("enddate").disabled == false){
document.getElementById("enddate").disabled = true;
document.getElementById("endtime").disabled = true;
document.getElementById("enddate").value = null;
document.getElementById("endtime").value = null;
}
else{
document.getElementById("enddate").disabled = false;
document.getElementById("endtime").disabled = false;
}
}
</script>
</body>
</html>
This is the php page fe_page2.php
<?php
require('dbconf.inc');
db_connect();
print"<pre>";
print_r($_POST);
print"</pre>";
$pipelocation = $_POST[pipelocation];
$pipetype = $_POST[Pipe-Type];
$pipeamount = $_POST[amount];
if($pipelocation=='value1' && $pipetype == 'value2' && $pipeamount == 'value3'){
$qrySel="SELECT `Pipe_ID`, `Location`, `Amount`, `PipeType` FROM pipe order by Pipe_ID desc";
$resSel = mysql_query($qrySel);
if($resSel){
while($rowpipe = mysql_fetch_array($resSel, MYSQL_ASSOC)){
echo "Pipe ID:{$rowpipe['Pipe_ID']} <br> ".
"Location: {$rowpipe['Location']} <br> ".
"Amount: {$rowpipe['Amount']} <br>".
"PipeType: {$rowpipe['PipeType']} <br>".
"--------------------------------<br>";
}
echo "Fetched Data Successfully!\n";
}
}
else{
echo"never went in!";
}
db_close();
?>
I have tried different things such as
if(isset($pipelocation) && isset($pipetype) && isset($pipeamount)){
.....
}
and removing the value from html page and using the following piece of code:
if($pipelocation == 'on' && $pipetype == 'on' && $pipeamount == 'on'){
...
}
But still no luck...
Any help would be appreciated.
The code that is presented is purely my work but does include pieces of code that comes from the provided reference below:
https://www.youtube.com/watch?v=LZtXYa9eGGw
You missed the quotations here:
$pipelocation = $_POST['pipelocation'];
$pipetype = $_POST['Pipe-Type'];
$pipeamount = $_POST['amount'];

How to set field value as the result of a calculation

I have a form that has a field whose value is from a php calculation. The Calculation is just basic arithmetic involving purely whole numbers. But there is a scenario where the value will be zero. So the form assumes that that filed has been left empty.
How can i go round that ?
Here is a sample of code.
if (
isset($_POST['input1']) &&
isset($_POST['input2']) &&
isset($_POST['ans'])
)
{
// CHECKING IF ANY OF THE FIELDS WERE LEFT EMPTY
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$ans = ($input1)-($input2);
$ans_set = 0;
if ($ans === $ans_set ) {
# code...
//echo "Same";
$ans = '0';
} else {
# code...
//echo "Different";
echo "Check data types";
}
if (
!empty($input1) &&
!empty($input2) &&
!empty($ans)
)
{
$query = "INSERT INTO formaths VALUES ( 'NUll', NOW(),
'".mysql_real_escape_string($input1)."',
'".mysql_real_escape_string($input2)."',
'".mysql_real_escape_string($ans)."' )";
$query_run = mysql_query($query);
if ( $query_run )
{
//header("Location:". __DIR__."../registration_success.php");
echo "<p class='echo'>Data entry was successful.</p>";
}
else
{
echo "<p class='echo'>It seems that we couldn't save that at this time.</p>";
}
}
else
{
echo "<p class='echo'>Please make sure all fields are filled and are correct.<br/>You must fill in the area field last!</p>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="formaths.php" method="POST">
<input name="input1" type="text" autofocus/>
<input name="input2" type="text"/>
<input name="ans" type="text" value="<?php if (isset($ans)) { echo $ans; }?>" readonly />
<input type="submit" value="DO IT" />
</form>
enter code here
</body>
</html>

Checking if the input name and telephone number valid with php

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.

Help PHP and HTML Checkboxes

I need help working with Checkboxes and PHP. I'm just trying to determine a value on whether the checkbox is checked or not with PHP.
Example:
<?php
include ("inc/conf.php");
$id = $_SESSION['id'];
if(isset($_POST['subfrm'])){
$gtid = $_REQUEST['tid'];
$ch1 = $_REQUEST['ch1'];
if($ch1 == "ON"){
$gch1 = "Y";
} else {
$gch1 = "N";
}
$ch2 = $_REQUEST['ch2'];
if($ch2 == "ON"){
$gch2 = "Y";
} else {
$gch2 = "N";
}
mysql_query("UPDATE SET ctable ch1='$gch1', ch2='$gch2' WHERE id='$gtid'");
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="tid" value="<?php echo $id; ?>" />
<input type="checkbox" name="ch1" />Hats
<input type="checkbox" name="ch2" />Watches
<textarea name="thetext"></textarea>
<input type="submit" name="subfrm" value="PUNCH ME" />
</form>
if(isset($_REQUEST["ch1"])){
$gch1 = "Y";
} else {
$gch1 = "N";
}
if(isset($_REQUEST["ch2"])){
$gch2 = "Y";
} else {
$gch2 = "N";
}
You don't need to check to see what the value is, because it will not submit any data whatsoever if it isn't checked, and it will submit a value of on if it is.
Try this:
<?php
$ch1 = isset($_REQUEST['ch1']);
If the check box wasn't checked, its corresponding variable won't show up in the request.
Through this together. It will let you know which checkbox was selected and it will also retain the check on form submit.
<?php
$message = '';
$ch1_checked = false;
$ch2_checked = false;
if(isset($_POST['submit_button'])) {
// Form was submitted
$ch1_checked = isset($_POST['ch1']);
$ch2_checked = isset($_POST['ch2']);
if($ch1_checked && $ch2_checked) {
$message .= 'Both were checked.';
} else if($ch1_checked) {
$message .= 'Checkbox 1 was checked.';
} else if($ch2_checked) {
$message .= 'Checkbox 2 was checked.';
} else {
$message .= 'Neither were checked.';
}
}
?>
<?php echo $message; ?>
<form id="my_form" action="test.php" method="post">
<input type="checkbox" name="ch1" value="ch1" <?php if($ch1_checked) echo 'checked'; ?> />Checkbox 1<br />
<input type="checkbox" name="ch2" value="ch2" <?php if($ch2_checked) echo 'checked'; ?> />Checkbox 2<br />
<input type="submit" name="submit_button" value="Go!" />
</form>

Categories