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

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

Related

Creating a simple php page that allows the user to input characters to search for names

I am trying to make a php page where we can input characters and select year of birth
After submitting it should show all the corresponding name but it doesn't work.
For example I input 'a' and the name containing 'a' having the same year as selected should appear.
This is my code:
In data.php I have like this
$person[0]=array('name'=>'Daniel','dateofbirth'=>2000);
$person[1]=array('name'=>'Gaetan','dateofbirth'=>1980);
My function.php
<?php
function comparator($word,$dateofbirth) {
include("data.php");
$p=1;
for($i=0;$i<count($person);$i++) {
$position=strpos(strtolower($person[$i]['name']),$word);
if($position === false) {
$p++;
}
else {
if($dateofbirth==$person[$i]['dateofbirth']) {
echo $person[$i]['name'] ;?><br /><?php
}
}
}
if($p==count($person)) {
echo "No results found";
}
}
?>
And the index.php, I used get method
I think my function.php is the problem but I don't know how to fix it.
I think this should solve your problem - https://3v4l.org/oQ1BC - however I feel it's necessary to say that it's inefficient and in production data are never stored that way, you should store the details of people in a database and connect to it and perform an SQL query. This only answers the original question.
function findPeople($searchString, $YoB, $listOfPeople){
$peopleFound = [];
foreach($listOfPeople as $individual){
if(strpos($individual['name'], $searchString) !== false && $individual['dateofbirth'] == $YoB){
$peopleFound[] = $individual;
}
}
return $peopleFound;
}
$listOfPeople = array();
$listOfPeople[0]=array('name'=>'Daniel','dateofbirth'=>2000);
$listOfPeople[1]=array('name'=>'Gaetan','dateofbirth'=>1980);
print_r(findPeople('a', 2000, $listOfPeople));

Showing the last error first instead of first(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];
}

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;
}

If statement working only until 1st else if [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I am trying to show a different navigation bar depending on a users authority. Only problem is that when i log on to the system it shows the first else if, regardless of the authority of the user. To ensure that the problem is in the loop i have tried switching the else ifs and the same happened. the code is in an external php file and i call the function in the top of each page. any suggestions ?
function checkAuth() {
session_start();
if(!isset($_SESSION['role'])) {
require_once('menu.php');
} else if ($_SESSION['role'] = "registered") {
require_once('regnav.php');
} else if ($_SESSION['role'] = "admin") {
echo "FDGFGFD";
require_once('adminnav.php');
}
}
Your issue is with this part: $_SESSION['role'] = "registered". The single = means you are assigning the value "registered" to variable $_SESSION['role'].
If you are evaluating to check something, you need to use == i.e. $_SESSION['role'] == "registered"
You'll have the same issue with the second elseif
You need to use a double = sign for any condition check. For any condition check in if or else if, you have to use == in the middle of the variables.
If you use only = that means it assigning the value in the $_SESSION['role']. Also you can use === for checking the value as well as the type of the variable.
Valid function is:
function checkAuth()
{
session_start();
if(!isset($_SESSION['role']))
{
require_once('menu.php');
}
else if ($_SESSION['role'] == "registered"){
require_once('regnav.php');
}
else if ($_SESSION['role'] == "admin"){
echo "FDGFGFD";
require_once('adminnav.php');
}
}
?>

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).

Categories