I'm trying to learn validation and below is where a form for user to enter the 4 fields which I need to validate the user's entry.
1st question: For the variable $a to check if there's content in error array, where should I define it ?
2nd question: for each field(productname/desc/cat/price), should i create a different array to store the error message ?
<?php
$productName = filter_has_var(INPUT_GET, 'pName') ? $_GET['pName']: null;
$desc = filter_has_var(INPUT_GET, 'description') ? $_GET['description']: null;
$cat = filter_has_var(INPUT_GET, 'category') ? $_GET['category']: null;
$pPrice = filter_has_var(INPUT_GET, 'price') ? $_GET['price']: null;
$productName = trim ($productName);
$desc = trim ($desc);
$cat = trim ($cat);
$pPrice = trim ($pPrice);
echo "<h1>Product details</h1>\n";
$nameerror = array();
if (empty($productName))
{
$nameerror[] = "You have not enter a Product";
}
elseif (strlen($productName) >50)
{
$nameerror[] = "Exceed product field length";
}
if (empty($desc))
{
$nameerror[] = "You have not enter description in the Description field";
}
elseif (strlen($desc) >100)
{
$nameerror[] = "Exceed descrption field length";
}
if (empty($cat))
{
$nameerror[] = "You have not enter category in the Category field";
}
if (empty($pPrice))
{
echo"<p>You have not enter price in the Price field</p>\n";
}
elseif (strlen($pPrice) >10)
{
echo"<p>Exceed price field length</p>\n";
}
if (!empty($nameerror))
for ($a=0;$a<count($nameerror);$a++)
{
echo "$nameerror[$a] <br />\n";
}
else
{
echo "<p>Name: $productName</p>\n";
echo "<p>Description: $desc</p>\n";
echo "<p>Category: $cat</p>\n";
echo "<p>Price: $pPrice</p>\n";
}
?>
Your aim is to collect all the errors in the form and tell the user of those.
Everything is correct except that you are using the wrong array name in your loop. It should be:
for ($a=0;$a<count($nameerror);$a++)
{
echo "$nameerror[$a] <br />\n";
}
Answer to your second question is: No - you can store all your error messages in a single array just as you have already done.
Related
Heyo newbie to PHP here,
I'm creating a registration form where the user is able to select how many family members are in the family, Depending on the number selected the same number of fields would be created to allow them to enter family members' details.
The form checks if all error messages are empty before starting the database insert.
I've been trying for hours though still not sure what's causing the array to return empty() - False,
Full Code -
GDrive Share Link
Creation of the Arrays
$MemberNameErr = array();
$MemberDOBErr = array();
Giving the Array values based on the number of Family Members
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter;
$Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
If function that checks that no errors have been made
if ($FamilyNameErr == "" && $DateErr == "" && $EmailErr == "" && $PhoneErr == "" && $MobileErr == "" && empty($MemberNameErr) && empty($MemberDOBErr))
{
currently using empty() as a way to check if the array is empty
created these just to check if the arrays were Not Empty
if (!empty($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (!empty($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
Thank you for all your input.
In your loop
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter; $Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
You're assigning empty string to indexes of the array. This means the array isn't empty anymore.
In example :
$tab = array("", "", "");
if (empty($tab))
{
echo "Empty";
}
else
{
echo "Not empty";
}
Output :
Not empty
A workaround could be to iterate through this array and check if there's at least 1 non empty string.
In example
function CheckNonEmptyValue($arr)
{
foreach ($arr as $value)
{
if (!empty($value))
{
return (true);
}
}
return (false);
}
if (CheckNonEmptyValue($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (CheckNonEmptyValue($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
Let's say I have search.php and edit.php.
Inside the search.php they can remove and update some records.
If the user clicks the "update" button, the system will redirect the user to another page called edit.php.
I successfully called the itemid.
but this happens..
<?php
$itemid = $_GET["itemid"];
$description = "";
$classification = "";
$unit = "";
$quantity = "";
$price = "";
$reorder = "";
$status ="";
$record = MYDB::query(
"select
*
from
item
where
itemid = ? ",
array($itemid),
"SELECT"
);
if(count($record) > 0)
{
$record = $record[0];
$description = $description['description'];
$classification = $classification['classification'];
$unit = $unit['unit'];
$quantity = $quantity['quantity'];
$price = $price['price'];
$reorder = $reorder['reorder'];
$status = $status['status'];
}
else
{
echo '<div class="fail">';
echo '<b>FAIL!</b> Item Not Found!</div>';
die();
}
if(isset($_POST["btnsubmit"]))
{
if(isset($_POST["description"])){
$description=ucwords(trim($_POST["description"]));
}
else{
echo "Please Enter description";
}
if(isset($_POST["classification"])){
$classification=ucwords(trim($_POST["classification"]));
}
else{
echo "Please Enter classification";
}
if(isset($_POST["unit"])){
$unit=ucwords(trim($_POST["unit"]));
}
else{
echo "Please Enter unit";
}
if(isset($_POST["quantity"])){
$quantity=ucwords(trim($_POST["quantity"]));
}
else{
echo "Please Enter quantity";
}
if(isset($_POST["price"])){
$price=ucwords(trim($_POST["price"]));
}
else{
echo "Please Enter Price";
}
if(isset($_POST["reorder"])){
$reorder=ucwords(trim($_POST["reorder"]));
}
else{
echo "Please Enter reorder";
}
if(isset($_POST["status"])){
$status=ucwords(trim($_POST["status"]));
}
else{
echo "Please Enter status";
}
}
?>
This are the errors,
Warning: Illegal string offset
Notice: Uninitialized string offset: 0
That error basically means that you are calling an array by a key which does not exist. I would tell you which key that is but you have not provided the specific variable.
Say I have this array:
$array = ('some_real_key' => 'a very important value');
Now if I call this $array['some_fake_key'], given that our array does not have that some_fake_key then it will produce the error you are seeing. Same goes for your 0 offset.
You are calling it in your code:
$record = $record[0];
That means that there's no 0 offset, which could mean a range of things... Again there's not enough data provided. But it would follow the same example as above.
To fix those issues you can use array_key_exists():
if ( array_key_exists( 'some_real_key', $array )
{
echo $array['some_real_key'];
}
else if ( array_key_exists( 'some_fake_key', $array )
{
echo $array['some_fake_key'];
}
This will output only the first array key; and will output no errors.
UPDATE
Thinking about it, I think your error may be produced from your variables as follows:
$record = $record[0];
$description = $description['description'];
$classification = $classification['classification'];
$unit = $unit['unit'];
$quantity = $quantity['quantity'];
$price = $price['price'];
$reorder = $reorder['reorder'];
$status = $status['status'];
You are not really setting them from an array; you may be wanting to call $record['key'] instead of $description = $description['description'];
For instance this would look like:
$description = $record['description'];
// ... so on ...
This looks like the culprit
$record = $record[0];
You cant be setting a variable as a none array with itself becoming an array with an uninitialized value. That's just crazy talk... :)
What do you think you are trying to do with that line?
Assuming $record[0] exists and its some kind of id, you could do...
$record_id = $record[0];
But you are using an associative array for all your other items, so where does the index of 0 come into the picture...
You'd need to perform a var_dump of $record to check you are getting what you expect.
So in the form I have this input
<input type="text" name="squareFoot" value="<?PHP if(isset($_POST['squareFoot'])) echo $squareFoot ?>"><span class="error_message"><?PHP echo " " . $squareFootError; ?></span>
And here's my validation (which is yes above the form)
if(isset($_POST['submit'])){
$isSubmitted = true;
$squareFoot = $_POST['squareFoot'];
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_SPECIAL_CHARS);
if(!is_numeric($squareFoot)){
$isValid = false;
$squareFootError = "Please enter a numeric value";
}
else if(empty($squareFoot)){
$isValid = false;
$squareFootError = "Please enter a numeric value";
}
else if($squareFoot < 200){
$isValid = false;
$squareFootError = "Please enter a number between 200 and 500,000";
}
else if($squareFoot > 500000){
$isValid = false;
$squareFootError = "Please enter a number between 200 and 500,000";
}
else{
/// do math (code not shown)
// Format Square Footage
$squareFootFormat = number_format($squareFoot, 0, '', ',');
// Display to user
<p>1. Square Footage being stripped <span class="right_al"><?PHP echo $squareFootFormat; ?></span></p>
So I have it set up so that the user can't put in html or script, the user must put in a number that has to be between two numbers, and that number can have a comma.
I also want the user to be able to put in something like 500.5, but when testing 500.5 turns into 5,005.
Is it because of
$squareFootFormat = number_format($squareFoot, 0, '', ',');
Or is something else wrong with it?
I kinda want to keep the number_format() in because it makes the number easier to read if it's some large number like 100,000. Can I do that?
Thanks for helping.
Your filter_var is not going to allow 500.5 as a value.
$squareFoot = filter_var($squareFoot, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
What about only doing this:
<?php
$squareFoot = $_POST['squareFoot'];
$smallest = 1;
$greatest = 100000;
if(is_numeric($squareFoot)) {
if($squareFoot < $greatest && $squareFoot > $smallest) {
//do what you want
echo number_format($squareFoot, 1, '.', ',');
}
else {
echo "Please enter a number between " .$smallest . " and ".$greatest;
}
}
else {
echo "Please enter a numeric value";
}
?>
Looks simplier to me.
I'm trying to validate data but I'm having trouble.
The problem is I am checking if certain post data is set. Problem is it's either always set or not, i think it's because I am trying to check for multiple things in an incorrect format in my if statement?
I think it's only this line that is incorrect but I am having some sort of mental block.
I understand it is probably something quite trivial but I can't think of a way to word it to find a solution via Google.
if ((!isset($_POST['first_name'])) || (!isset($_POST['contact_no'])) || (!isset($_POST['device'])) || (!isset($_POST['fault']))) {
echo 'no Name, contact number, device or fault given.';
}
I know i could check in separate if's but I would really like to refresh how i check multiple items in the same statement..
After trying suggestions, without any luck, adding more information:
if (isset($_POST['posted']) == 'TRUE') {
$error = array();
if( !isset($_POST['first_name']) ){ $error[] = 'no Name given.'; }
elseif( !isset($_POST['contact_no']) ){ $error[] = 'no contact number given.'; }
elseif( !isset($_POST['device']) ) { $error[] = 'no Device given.'; }
elseif( !isset($_POST['fault']) ) { $error[] = 'no fault given.'; }
if( count($error)!==0){
echo 'Error(s) occured:<br />'.implode('<br />', $errors);
}
else {
$db->query("INSERT INTO repairs (r_oem, r_device, r_mod, r_reserve, r_price, r_s_date, r_e_date, r_notes, rc_fname, rc_lname, rc_email, rc_contactno, rc_return, rc_status, rc_status_2, rc_status_txt, rc_status_txt_2, booked_by, passcode) VALUES( '$make', '$device', '$model', '$fault', '$price', '$date', '$date2', '$notes', '$fname', '$lname', '$email', '$cno', '','$status', '', '', '', '$bookedby', '$pass')");
$get_id = $db->query("SELECT LAST_INSERT_ID()");
$print_id = $db->fetch_row($get_id);
$last_r_id_insterted = $db->query("SELECT * FROM `repairs` ORDER BY `repairs`.`r_id` DESC LIMIT 1");
$plrid = $db->fetch_row($last_r_id_insterted);
echo '<br />';
echo <<<EOF
<script>
alert("Successfully created record for {$fname} {$lname}\'s {$make} {$device} {$model}. Job Reference: {$plrid['r_id']}");
</script>
EOF;
print "<span style='float: left; margin-left:25px;'><a class='button positive' 'href=\"print_label.php?ref={$plrid['r_id']}\" target=\"_blank\">Printable Sticky Label.</a></span><span class='fright'><a class='button positive' href=\"print_card.php?ref={$plrid['r_id']}\" target=\"_blank\">Printable Customer Card.</a></span><br /><br />";
if (isset($_POST['item1'])) {
$db->query("UPDATE repairs SET part1id={$_POST['item1']} WHERE r_id={$plrid['r_id']}");
$db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item1']}");
}
if (isset($_POST['item2'])) {
$db->query("UPDATE repairs SET part2id={$_POST['item2']} WHERE r_id={$plrid['r_id']}");
$db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item2']}");
}
if (isset($_POST['item3'])) {
$db->query("UPDATE repairs SET part3id={$_POST['item3']} WHERE r_id={$plrid['r_id']}");
$db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item3']}");
}
if (isset($_POST['item4'])) {
$db->query("UPDATE repairs SET part4id={$_POST['item4']} WHERE r_id={$plrid['r_id']}");
$db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item4']}");
}
if (isset($_POST['item5'])) {
$db->query("UPDATE repairs SET part5id={$_POST['item5']} WHERE r_id={$plrid['r_id']}");
$db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item5']}");
}
else {
print "No Parts Selected<br />";
}
}
}
You can check $_POST vars with
if(isset($_POST))
{
}
and then validate every single key of $_POST var
if(isset($_POST))
{
if(!isset($_POST['first_name']))
echo "no name";
elseif(!isset($_POST['contact_no']))
echo "no number";
}
I think you want to use something like
$_POST['first_name'] == ""
I believe that as long as the field first_name is included in the form, it isset() even if it does not contain any data.
Sample code (submit the form with and without the input field filled in, same results:
<?php
if (isset($_POST['first_name'])) {
echo "it's set!";
}
?>
<form method='post'>
<input type='text' name='first_name'/>
<input type='submit' value='submit'/>
</form>
First of, you can compact it a lot by joining the values in isset:
if ( isset($_POST['first_name'], $_POST['contact_no'], $_POST['device'], $_POST['fault']) ) {}
Please note that I dont use the ! to reverse. isset() returns false if one of the values is not set.
I think you are looking for if( isset($_POST) ){ /* ... */ }.
Apart from that, I'm not really sure what you mean, but I think something like this:
if( isset($_POST) ){
if( !isset($_POST['first_name']) ){ echo 'no Name given.'; }
elseif( !isset($_POST['contact_no']) ){ echo 'no contact number given.'; }
elseif( !isset($_POST['device']) ) { echo 'no Device given.'; }
elseif( !isset($_POST['fault']) ) { echo 'no fault given.'; }
else{
echo "everything OK";
}
}
Another method would be concating strings:
if( isset($_POST) ){
$error = array();
if( !isset($_POST['first_name']) ){ $error[] = 'no Name given.'; }
elseif( !isset($_POST['contact_no']) ){ $error[] = 'no contact number given.'; }
elseif( !isset($_POST['device']) ) { $error[] = 'no Device given.'; }
elseif( !isset($_POST['fault']) ) { $error[] = 'no fault given.'; }
if( count($error)!==0){
echo 'Error(s) occured:<br />'.implode('<br />', $errors);
}
else{
echo "everything OK";
}
}
I would probably create a function:
function fieldIsSet($field) {
if(is_array($field) {
foreach($field as $f) {
if( ! fieldIsSet($f)) {
return false;
}
}
} else {
if( !isset($_POST[$field]) || empty($_POST[$field])) {
return false;
}
}
return true;
}
Usage:
// with an string[]
fieldIsSet(array('first_name', 'contact_no', 'device', 'fault')) or echo 'no Name, contact number, device or fault given.';
// with a single string
fieldIsSet('first_name') or echo 'no Name given.';
I think it can be solved by using
if($_POST.length<4){…your code…},
assuming that you send only 4 variables through the post request.
My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.