Undefined index when calculating age from an inputted birthdate - php

I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code
This is my code for inputting Birthdate:
input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required
And here's my code for calculating age:
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
$dob = $_POST["P_Bday"];
And I call my function here, where it should display the calculated age depending on the inputted birthdate:
input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly
Every time I ran my code it says:
Notice: Undefined index: P_Bday in
C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line
47

If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.
Change the line to:
if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
else $dob = null;
Or:
$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;

An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.
The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.
Example
if (!isset($_POST['P_Bday'])) {
die("You forgot to fill out your birthday!");
} else {
echo "Yay!";
}
Some good initialization techniques with $_POST/$_GET
A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.
Example
$defaultValues = [
'P_Bday' => null,
'Option1' => 'default',
'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;
/**
* Now you can pass around $inputValues safely knowing all expected values
* are always going to be initialized without having to do isset() everywhere
*/
doSomething(Array $inputValues) {
if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
throw new Exception("You didn't give a birthday!!!");
}
return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}

You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following:
Please write your code as follows:
if(isset($_POST["P_Bday"])){
$dob = $_POST["P_Bday"];
} else {
$dob ="";
}
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}

Related

Using Dynamic Variable Names to Call Static Variable in PHP

I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:
23 $level = $_SERVER['DEBUG_LEVEL'];
24 $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});
When I do this, the code fails with the error:
A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.
How would I use a specific Logger:: level in this way?
UPDATE:
I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.
However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.
The variable itself is declared here
PHP Version => 5.6.99-hhvm
So the answer was to use a function for a constant lookup:
$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));
<?php
class Logger {
const MY = 1;
}
$lookingfor = 'MY';
// approach 1
$value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor];
// approach 2
$value2 = constant("Logger::" . $lookingfor);
echo "$value1|$value2";
?>
Result: "1|1"

Changing module name

I am customising a opensource phreebooks. I want to change the module names in that. I did change the module names for phreebooks and phreedom successfully, but when i change the name for phreedom i can not print any pdf. I am getting this error
User: 1 Company: phree RUN-TIME WARNING: 'Creating default object from empty value' line 50 in file
F:\wamp\www\phree\modules\report\pages\popup_gen\pre_process.php
In line no 50, code is like this
if (isset($_GET['xfld'])) $report->xfilterlist[0]->fieldname = $_GET['xfld'];
Can somebody please tell me where exactly i am doing wrong. I have been tying it from past 3 days.
EDITED
if (isset($_GET['xfld'])) { // check for extra filters
if (!isset($_GET['xfld'])) $xfld = new stdClass();
echo "BLANK";
if (isset($_GET['xfld'])) $report->xfilterlist[0]->fieldname = $_GET['xfld'];
if (isset($_GET['xcr'])) $report->xfilterlist[0]->default = $_GET['xcr'];
if (isset($_GET['xmin'])) $report->xfilterlist[0]->min_val = $_GET['xmin'];
if (isset($_GET['xmax'])) $report->xfilterlist[0]->max_val = $_GET['xmax'];
}
i did like this
It displays "BLANK" but actually isset($_GET['xfld'] is SET from URL.
$_GET['xfld'] = $xfld;
$xfld = NULL;
$xfld->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $xfld is already initialized to some value but is not an object:
$xfld = something;
$xfld->success = false; // Warning: Attempt to assign property of non-object
You shoud check whether the object already exists:
if (!isset($_GET['xfld'])) $xfld = new stdClass();
Otherwise, this code is not an equivalent replacement for the "old PHP" implicit object creation.

Call to undefined method stdClass

I am occasionally getting the PHP Fatal error: Call to undefined method stdClass::transition() in agent.php on line 25 (I marked line 25 in the code). This code is called often, so struggling to see why it is happening.
Here is the snippet of agent.php that calls the
function agent_exam_complete($exam){
$ce = $exam->educational();
$ce->exam_id = $exam->exam_id;
$ce->exam_grade = $exam->score;
$ce->exams_remaining -= 1;
$ce->exam_received_date = sql_now();
if($exam->status()=='passed'){
$ce->transition('passed');
}elseif($ce->exams_remaining <= 0){
$ce->transition('failed');
}
$ce->save();
if($ce->is_certification_completed($ce->certification_id, $ce->client_no)){
agent_certification_complete($ce->certification_id, $ce->client_no);
}
}
function agent_certification_complete($certification_id, $client_no){
$ce = ClientPurchase::find('first', array('conditions' => "certification_id = '$certification_id' and is_certification = 1 and client_no='$client_no'"));
$ce->certification_date = date('Y-m-d');
$ce->transition('passed'); **//Line 25**
$ce->save();
}
transition() is defined in another file and is called often. I've included a little bit of it's code just for flavor.
function transition($event_tag){
$old_status = $this->status;
$next_status = $this->next_status_for_transition($event_tag);
if($next_status==''){
return; }
$this->status = $next_status;
My question is, why am I only getting this error periodically and not all the time? What can I do to eliminate the error and subsequent blank screen for my clients? I've only noticed that it is happening to those with Firefox or Chrome.
Thanks in advance,
Jim
The object $ce that contains the function is being generated multiple times. I suppose this is so transition is customized for whatever object is called.
Why not create another object for re-useable functions? Consider expanding the function so that it is compatible with all objects that would use it.
$my = new functionClass;
class functionClass
{
function transition()
{
$old_status = $this->status;
$next_status = $this->next_status_for_transition($event_tag);
if($next_status==''){
return; }
$this->status = $next_status;
}
}
$my->transition( 'passed' );
Something like that would cut down on unpredictability and I believe may solve your problem.
Try this little snippet of code to see whats going on:
$ce = false;
$ce->certification_date = date('Y-m-d');
var_dump($ce);
In this case $ce get cast to an object of stdClass when you try to set a property (certification_date).
Now your code:
function agent_certification_complete($certification_id, $client_no){
$ce = ClientPurchase::find('first', array('conditions' => "certification_id = '$certification_id' and is_certification = 1 and client_no='$client_no'"));
//$ce is probably false or null
//it gets cast to a stdClass object
$ce->certification_date = date('Y-m-d');
//stdClass does not have a transition method; ERROR
$ce->transition('passed'); **//Line 25**
$ce->save();
}
So in your code, if find() is returning null or false, or maybe some other choice values, $ce gets cast to a stdClass object on the next line. Then that stdClass object does not have a transition() method so you get an error.
To fix this, either adjust your find method or check its return value and handle accordingly.
As to it happening only in certain browser, I think thats a false conclusion. If find() is calling a query, it probably only happens at certain times depending on the result of that query.

CakePHP Notice (8) raised : Use of undefined constant inList - assumed 'inList'

Notice (8): Use of undefined constant inList - assumed 'inList' [CORE\Cake\Utility\ClassRegistry.php, line 168]
This notice has been bugging me for a while know, and I do not know how to fix it.. It was not really affecting my project earlier since its just a notice msg, but now, it is not letting me show an error message which I am trying to display to the user.
Iv got this function
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['Donor'][$this->params['form']['field']] = $this->params['form']['value'];
$this->Donor->set($this->data);
if($this->Donor->validates()){
$this->autoRender = FALSE;
}else{
$error = $this->Donor->validationErrors;
$this->set('error',$error[$this->params['form']['field']]);
}
}
}
The above is the action to which my post request submits to. Then it executes the following to display the error
if (error.length > 0) {
if ($('#name-notEmpty').length == 0) {
$('#DonorName').after('<div id="name-notEmpty" class="error-message">' + error + '</div>');
}
}else{
$('#name-notEmpty').remove();
}
The problem is that instead of the relevant error in my newly created div... I get that notice 8 from cake! Please if anyone knows why this is happening, I appreciate your aid on this one..
TLDR:
Do a project-wide find for 'inList' and find the spot where it either doesn't have quotes around it, or, if it's supposed to be a variable, is missing it's $.
Explanation:
You get that error when you try to use a PHP Constant that doesn't exist. Usually you're not actually TRYING to use a constant, but instead just forgot to wrap quotes around something or forgot to add the $ before a variable.
Examples:
$name = "Dave";
echo name; // <-- WOAH THERE, there is no Constant called name (missing $)
$people = array('Dave' => 'loves pizza');
echo $people[Dave]; // <-- WOAH THERE, no Constant called Dave (missing quotes)
Most likely somewhere else in your code you are using 'inList' as an array key but you don't have it quoted.
Example: $value = $myArray[inList];
It still works without quoting inList but it causes the notice message you're seeing.

Preventing PHP to show notices for undefined arguments when using exceptions

I think the question is fairly self-explainatory, here's the code:
HTTP Request: localhost/execute.php?password=testing&command=create&api=api
This is part of the execution code.
try
{
$TFA_SAMP->createUser($_GET['email'], $_GET['cellphone'], $_GET['area_code']);
}
catch(Exception $createError)
{
echo $createError->getMessage();
}
Here's the class method:
function createUser($email, $cellphone, $areaCode = 1)
{
if(!isset($email))
throw new BadMethodCallException('(CTFA_SAMP->createUser) email ('. $email .') is missing.');
if(!isset($cellphone))
throw new BadMethodCallException('(CTFA_SAMP->createUser) cellphone ('. $cellphone .') is missing.');
$authyLibrary = new Authy_Api($this->API, $this->connectionURL);
$requestResult = $authyLibrary->registerUser($email, $cellphone, strval($areaCode));
if($requestResult->ok())
{
echo $requestResult->id();
}
else
{
foreach($requestResult->errors() as $field => $message)
echo "$field = $message";
}
}
The PHP pages prints:
Notice: Undefined index: email in D:\xampp\htdocs\tfasamp\execute.php on line 46
Notice: Undefined index: cellphone in D:\xampp\htdocs\tfasamp\execute.php on line 46
Notice: Undefined index: area_code in D:\xampp\htdocs\tfasamp\execute.php on line 46
(CTFA_SAMP->createUser) email () is missing.
How do I prevent PHP from giving me those notices as I am using exceptions to show them?
$TFA_SAMP->createUser($_GET['email'], $_GET['cellphone'], $_GET['area_code']);
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
The non-existing variables are accessed here. Nobody cares that you're later checking for isset on completely different variables and are throwing exceptions, the problem is in the above line. You need to fix it there. For example:
$args = $_GET + array('email' => null, 'cellphone' => null, 'area_code' => null);
$TFA_SAMP->createUser($args['email'], $args['cellphone'], $args['area_code']);
Alternatively, use isset statements here and throw exceptions for missing user input.
Basically, the code which touches $_GET deals with completely unpredictable user input. That's your first line of defence in which you need to check for existing or non-existing values. You can't roll this as responsibility into code which comes later.

Categories