Showing the last error first instead of first(php) - php

I have a login form currently setup that confuses my users.
The way i handle errors is like this;
if (!($result->total > 0)) {
$err[] = "License key is not in our system.";
}
if ($claimed == 1) {
err[] = 'License key has been claimed already.';
}
if ($userID > 0) {
$err[] = 'License key is already connected to a user.';
}
if ($banned == 1) {
$err[] = 'License key is banned';
}
so for example, if one of my users would input a invalid license key instead of showing that it is not in our system it would show banned(creating confusion). Because i'm not exiting the code and letting it run.
I'm wondering how to go on about error handling when my functions are set up like this.
update -
Forgot to show how i'm displaying the error.. my fault!
if (empty($err)) {
//no errors
} else {
echo $err; //this will show the last error instead of the first error generated
}

OK Bob,
It would be helpful if you were showing us how you are presenting your errors, as what you are explaining would suggest that your $err array would then contain two values, not just (the last) one.
However, what I think is going on here is that your $banned condition will always be met; unless you add another = to your if statement, like this:
if (!($result->total > 0)) {
$err[] = "License key is not in our system.";
}
if ($claimed == 1) {
err[] = 'License key has been claimed already.';
}
if ($userID > 0) {
$err[] = 'License key is already connected to a user.';
}
if ($banned == 1) { # <-- Here
$err[] = 'License key is banned';
}
Then for testing purposes you can view the array of errors:
if(isset($err) && !empty($err)){
print_r($err);
}
If you want to loop through each potential error:
if(isset($err) && !empty($err)){
foreach($err as $error){
echo "Error because: {$error}".PHP_EOL;
}
}

So you are adding all the errors to the array err.
To display the first item in an array, just use [0] to access the first index.
if (empty($err)) {
//no errors
} else {
echo $arr[0];
}

Related

Showing the last error first instead of first in PHP [duplicate]

This question already has answers here:
Showing the last error first instead of first(php)
(2 answers)
Closed 3 years ago.
I have a login form currently setup that confuses my users.
The way i handle errors is like this;
if (!($result->total > 0)) {
$err[] = "License key is not in our system.";
}
if ($claimed == 1) {
err[] = 'License key has been claimed already.';
}
if ($userID > 0) {
$err[] = 'License key is already connected to a user.';
}
if ($banned == 1) {
$err[] = 'License key is banned';
}
so for example, if one of my users would input a invalid license key instead of showing that it is not in our system it would show banned(creating confusion). Because i'm not exiting the code and letting it run.
I'm wondering how to go on about error handling when my functions are set up like this.
this is how i'm displaying the error..
if (empty($err)) {
//no errors
} else {
echo $err; //this will show the last error instead of the first error generated
}
quite simple:
if (empty($err)) {
//no errors
} else {
array_reverse($err);
echo array_pop($err); //this will show the first error generated
}
You are creating an array of errors so you can always loop through the array using foreach loop
Foreach($err as $val)
{
echo $val;
}
Other wise $err will always print the last error.
Hope it helps

vTiger Event Handler to check if record exists

I am working on vTiger 6.5 and I am trying to figure a way to see if a record exists in a custom module of mine. I want to check whether the 'policynumber' is new before saving, here is my code so far. For some reason it seems to act randomly depending on my module number chosen.
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {
$isNew = $entityData->isNew('policynumber');
if ($isNew == false) {
echo "Duplicate policy number";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave') {}}
if($eventName == 'vtiger.entity.beforesave.final') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
if($eventName == 'vtiger.entity.aftersave') {}
}
}
At the moment I am currently using an echo just to see the result. But later on I will perform more than this.
isNew()
Returns true if new record is being created, false otherwise.
More info is here
you should write a custom query to check policynumber already exist or not in your function:
if($eventName == 'vtiger.entity.beforesave.modifiable') {
global $adb;
$result = $adb->pquery("SELECT your-field-name FROM table_name WHERE policynumber=?", array($policynumbervalue));
if($result && $adb->num_rows($result)) {
echo "This policy number exist";
die();
}else{
// write your overwrite code
}
} //end if($eventName == 'vtiger.entity.beforesave.modifiable')
Update:
I am assuming there is field i.e. policynumber in your form, you enter some value in this field and submit the form. so you will get entered policy number value from this:
$policynumbervalue = $entityData->get('policynumber'); //this is vtiger standard way
if this does not work, you can simply use php global variable $_REQUEST['policynumber'] but I is not a good practice.
Hope this will help.
This is the update to my answer, I simply done an if statement on the number of rows displayed.
if($eventName == 'vtiger.entity.beforesave.modifiable') {
$policynumbervalue = $entityData->get('policynumber');
$sql = $adb->pquery("SELECT policynumber FROM vtiger_isa WHERE policynumber=?",array($policynumbervalue));
$nrows = $adb->num_rows($sql);
if($nrows > 0){
echo "<script type=\"text/javascript\">window.alert('ISA policy number already exists, you will be redirected to the updata module.');
window.location.href = '/vtigercrm/index.php?module=isa&view=List';</script>";
exit;
}

Echo content inside foreach only once

I'm trying to echo content inside a foreach once. At the moment, when a form is filled by the user, the message is displayed for every record skipped. If there are 35 records skipped, I will get 35 messages, because of the foreach. I want to avoid this, and be able to display only one echo for the entire results page. How can I do this? I suppose I may have to do this outside the foreach, but I have no clue how to take it out of the foreach.
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
if($course->aircraft == '2')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
Assuming you must maintain the structure of that object, you could just have a boolean update if $course->aircraft == 1 then echo accordingly:
$found = false;
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$found = true;
}
}
}
}
if($found)
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
}
You can set a simple flag variable in this case.
$warningEmitted = false;
Then, in your loop prior to emitting a warning:
if(!$warningEmitted) {
// echo warning here.
$warningEmitted = true;
}
The best option would probably be to set your message as a variable, then echo the variable after the foreach is finished.
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$message = '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
if(isset($message))
{
echo $message;
}
Outside the loop assume $count=1;
Inside the loop, you can put an if statement.
if($count==1) { $count++; echo "Whatever";}
Hope this helps.
Just use a boolean variable which you set to false initially, and the set it to true in the loop if you get a match.
Then you can check the boolean after the loop has finished to decide if you need to display the message or not.
Create additional variable in which you will store information whether the message was already displayed or not. When you display it, set the var to true.
Assuming I understand you correctly, I think you want to use 'break' to stop looping as soon as a problem is found.
if (Auth::LoggedIn() && Auth::$userinfo->rank == 'Student') {
foreach ($allcourses as $course) {
if ($course->aircraft == '1') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
if ($course->aircraft == '2') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
}
}
Above I've also moved the "if logged in" conditional to be outside the loop (so it's only checked once).
Something to consider:
A more user friendly approach might to add each error into an array - instead of using echo & breaking out - and then loop through that error array at the end, showing with more information about the error so they can be corrected all at once by the end user (depending on how your form works, of course).

Dynamic if-statement with variables?

I'm trying to create a dynamic if-statement. The reason I want to do this, is because I need to check server-sided whether inputfields match my regex and are not empty. However, some of my inputfields can be removed in my CMS, meaning there would be more/less inputfields accordingly.
Ideally I would add variables in my if-statement but I'm not 100% sure if that's allowed, so perhaps I would need an other way to solve this problem. Here's what I tried:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = " || $_POST['streetname'] == ''"; //Used to check if field is empty
$pstreetname = " || !preg_match($streetnameReg,$_POST['streetname'])"; //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = ''; //Not needed in check
$pstreetname = ''; //Also not needed in check
}
// more of these if/else statements
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' $cstreetname $cpostalcode $chometown $ctelnr $csex $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
else
{
//Regex check, after that more code
}
My idea was to check if a specific field is shown on the front-end and in that case I'm creating some variables that I want to paste in my if-statements.
I'm getting an error saying Server error meaning my php-code would be invalid.
Is it even possible at all to make a dynamic if-statement? If yes, at what part am I failing?
Help is much appreciated! Thanks in advance.
First of all, since it looks like you need to combine all of the conditionals with ||, you can correct your program by writing it like this:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = $_POST['streetname'] == ''; //Used to check if field is empty
$pstreetname = !preg_match($streetnameReg,$_POST['streetname']); //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = false; //Not needed in check
$pstreetname = false; //Also not needed in check
}
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' || $cstreetname || $cpostalcode || $chometown || $ctelnr || $csex || $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
This would work, but it's unwieldy. A much better solution would be to use an array (let's name it $errors that gets dynamically populated with errors resulting from validating your fields. Like this:
$errors = array();
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
if ($streetname == '') {
$errors[] = 'Streetname cannot be empty.'; // message is optional
}
if (!preg_match($streetnameReg,$streetname)) {
$errors[] = 'Streetname is invalid.'; // message is optional
}
}
And then:
if ($errors) {
echo 'There are errors with the data you submitted.';
header('refresh:3;url=index.php');
}
If you provided human-readable error messages you can also arrange for them to be displayed so that the user knows what they need to fix. And of course there are lots of variations of this technique you can use -- e.g. group the error messages by field so that you only show one error for each field.
If you want to check for empty $_POST fields you can do something like this
$error = False;
foreach($_POST as $k => $v)
{
if(empty($v))
{
$error .= "Field " . $k . " is empty\n";
}
}
if(!$error)
{
echo "We don't have any errrors, proceed with code";
}
else
{
echo "Ops we have empty fields.\n";
echo $error;
}
And after you are sure that all the fields are not empty you can do other stuff.

PHP array not outputting properly

I am trying to do form validation but when I try to print out the contents of an array when there is an error it doesnt output anything.
$errors = array();
if (strlen($password) >= 6) {
array_push($errors, "Your password is not long enough! Must be over 6 characters!");
}
if(count($errors) !== 0) {
...
} else {
echo "There is errors<br/>";
foreach($errors as $er){
echo $er . "<br/>";
}
}
What I do get is "There is errors" so I know that the if else is working.
I just have to correct the argument of the if:
if(count($errors) === 0) {
// everything is okay
} else {
echo "There are errors<br/>";
foreach($errors as $er){
echo $er . "<br/>";
}
}
In this way, when your error count is 0, the content of the if is executed. When it isn't 0, the content of the else is executed and the errors are printed. It's just the opposite of what you did.
(I also corrected the sentence: it's ‘there are errors’, not ‘there is errors’ :P)
Furthermore, the other if is wrong as well, it should be the opposite:
if (strlen($password) <= 6) {
since you need to check when the password is less than 6 characters.
Shouldn't it be:
if (strlen($password) < 6) {
array_push($errors, ...);
?
BTW you should use at least constants instead of magic numbers, e.g.
define('MIN_PASSWORD_LENGTH', 6);
// ...
if (strlen($password) < MIN_PASSWORD_LENGTH) {
array_push($errors, "Your password is not long enough!"
. " Must be over ".MIN_PASSWORD_LENGTH." characters!");
}
This way, if your minimal required length changes, you just have to change it once.
Your if statement is messed up. You are checking for errors, then doing nothing, then the else is where it is displaying the errors. Try this:
if(count($errors) >0) { //there are errors
echo "There is errors<br/>";
foreach($errors as $er){
echo $er . "<br/>";
}
}else{
//there are no errors
}
Also, your password length should be <=6 not greater than or equal to if it is too short.

Categories