I am using XAMPP 1.7.2 (PHP 5.3) to devlope on winxp localhost.
There is a function works quite well. Comes from CodeIgniter Module.
function get_cal_eventTitle($year, $month){
$this->db->where('eventYear =', $year);
$this->db->where('eventMonth =', $month);
$this->db->select('eventTitle');
$query = $this->db->get('tb_event_calendar');
$result = $query->result();
foreach ($result as $row)
{
$withEmptyTitle = $row->eventTitle;
//echo $withEmptyTitle.'<br>';
$noEmptyTitle = str_replace(" ","%20",$withEmptyTitle);
$withUrlTitle = '<a href='.base_url().'index.php/calendar/singleEvent/'.$year.'/'.$month.'/'.$noEmptyTitle.'/'.'>'.$withEmptyTitle.'</a>';
//echo $withUrlTitle.'<br>';
$row->eventTitle = $withUrlTitle;
}
return $result;
}
When I upload my code to remote server(PHP 5.2.9). It show error as this,
withEmptyTitle undefined variable
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: withUrlTitle
Filename: models/calendar_model.php
Line Number: 54 // $withEmptyTitle = $row->eventTitle;
But When I enable the comment for the line echo $withEmptyTitle.'<br>';. It works well on remote server.
Assuming withEmptyTitle echo to Apr running event here.
I don't know why? Could you give me some suggestion to fix this issue? Appreciated for your input.
What you're seeing is probably not an error, but a warning.
PHP may be throwing the warning because you're using a variable that hasn't been initialised. It sounds likely that your local development PHP installation has warning messages supressed, whereas your live server has them enabled. (In fact, best practice would be to have it the other way round!)
In this case, it's possible that $withEmptyTitle = $row->eventTitle; is not initialising the $withEmptyTitle variable, if the eventTitle property is returning as unset. It would then fall following line and throw the warning when you try to use the variable in the str_replace() call.
You could avoid this warning by:
Switching warning message off in the PHP.ini
Doing ini_set() to switch it off during the program.
using isset($withEmptyTitle) to check that the variable is set prior to actually using it.
Ensuring that $row does actually contain an eventTitle property (in the context of your program, if it's missing, it may imply bad data or incorrect database table setup? In any case, you could change the SQL query to use IFNULL() or at least ensure the field is explicitly queried.
[EDIT]
I see you've edited the question. In particular, I note the following:
Line Number: 54 // $withEmptyTitle = $row->eventTitle;
I note the // .... does that imply that the line is commented out?? Have you somehow got a copy on the server which has that line commented? That would certainly explain the fact that you're getting warnings!
Related
I have upgraded my server to use PHP version 7.3 from 5.6
I ran compatibility check from PHPStorm for all my files, and it only showed me only weak warning for few of the codes but since I am no longer using those script I ignored it, but it does not point out anything wrong on this code.
But after migration, I found that this piece of code is not working as required. I have this code to get state short code when I pass the 2 digit country code.
$jsonitemfile = file_get_contents('countries-states.json');
$conobjitems = json_decode($jsonitemfile);
$findBystatename = function($constatename) use ($conobjitems) {
foreach ($conobjitems->$_POST['Contact0Country']->states as $short => $outputstate) {
if ($outputstate->name == $constatename) return $short;
}
return false;
};
$p2 = 'New York';
echo $findBystatename($p2) ?: $p2;
When I run this code I get the following error
Notice: Array to string conversion in /home/domain.com/public_html/code/code_check.php on line 27
Notice: Undefined property: stdClass::$Array in /home/domain.com/public_html/code/code_check.php on line 27
Notice: Trying to get property 'states' of non-object in /home/domain.com/public_html/code/code_check.php on line 27
Warning: Invalid argument supplied for foreach() in /home/domain.com/public_html/code/code_check.php on line 27
The same code is working on PHP 5.6 without throwing any error.
Although I fixed the code by doing the below changes
$findBystatename = function($constatename) use ($conobjitems) {
$p1 = $_POST['Contact0Country'];
foreach ($conobjitems->$p1->states as $short => $outputstate) {
if ($outputstate->name == $constatename) return $short;
}
return false;
};
For my learning curve can anyone please advise why its not working? And even with the updated code, if I define $p1 above the function, it start to throw the same error.
Also is there a way the original code start working on PHP 7.3 without updating the code?
$conobjitems->$_POST['Contact0Country']->state is ambiguous. It could mean the state property of an object defined by $conobjitems->$_POST['Contact0Country'] (as you and PHP 5.6 assume), or it could mean the state property of an object defined by $_POST['Contact0Country'] and then whatever that resolves to as a property on $conobjitems, which seems to be what modern PHP considers it.
Obviously a compiler/run time environment cannot treat a line as meaning two things, so it has to pick one and move on, or error out and fail. Historically PHP has been lenient in what it copes with, but as the language has improved and got faster some of that leniency has been removed in favour of making the coder be specific instead of ambiguous (which also helps make the code readable)
If this is just a toy example - this won't work, but your piece of code can be written as:
$jsonitemfile = file_get_contents('countries-states.json');
$conobjitems = json_decode($jsonitemfile);
$country=$conobjitems->$_POST['Contact0Country'];
$states=$country->states;
$findBystatename = function($constatename) use ($states) {
foreach ($states as $short => $state) {
if ($state->name == $constatename) return $short;
}
return false;
};
$p2 = 'New York';
echo $findBystatename($p2) ?: $p2;
$country could be skipped but it makes the code more readable, likewise separating the state list into $states before injecting into the closure makes it clear to the reader and PHP what you want to do.
By the way, since you seem to choose the country by user-input (which could be manipulated, even if you're using a drop down), you could also get an error, warning or exception when you create $country if that country doesn't exist in the $conobjitems set. You could use property_exists first to make sure the country is found.
This line of code worked perfectly before I upgraded, now it doesn't:
123: $thisRow[] = displayR(${"sR{$i}S1"}, ${"nR{$i}S1P"});
I get this error:
Undefined variable: sR1S1 in script.php on line 123
A workaround is to manually assign them first
$s = ${"sR{$i}S1"};
$n = ${"nR{$i}S1P"};
$thisRow[] = displayR($s, $n);
Is there anyway to get it working in a single line as before? Does anyone know why it no longer works?
I should add that I've tried using var_dump(${"sR{$i}S1"}); on the previous line and it IS defined, and has the value that I expect it to.
I can't find any mention of this behaviour on google or SO, I wonder if it's a bug rather than intended.
I believe this is to be an opcache bug.
Disabling opcache on the file in question resumed the expected behaviour.
I submitted a (fairly useless) bug report at:
https://bugs.php.net/bug.php?id=69159
Which has apparently been fixed and closed:
http://git.php.net/?p=php-src.git;a=commitdiff;h=a29b64fc1029b4121e3e9ff20901c35ad600b4da
I have just uploaded my project to my website server and i am getting this error message when i click on my submit button for my logging in form.
A PHP Error was encountered
Severity: Warning
Message: mysqli_real_escape_string() expects parameter 1 to be mysqli, boolean given
Filename: mysqli/mysqli_driver.php
Line Number: 315
I have absolutely no errors on my local server and i am completely stumped on what the problem is. if some one could please help i would be greatly appreciative and much respect will be given.
My project is using codeigniters framework.
mysqli_real_escape_string() is used to prepare text data too be save in an SQL Record Column.<br>And the data being wrint to that column does not exist.<br><br>
Go to mysqli_driver.php to Line #315 and put an at mark in fron of the command to supress the warning.
From:
mysqli_real_escape_string()
To:
#mysqli_real_escape_string()
If the value you are escaping is an integer, then use intval() instead:
This will turn a NULL into a Zero
$var = intval($var);
Instead of hide warnings with #, check that conn_id is not false:
change
$str = mysqli_real_escape_string($this->conn_id, $str);
like that
if($this->conn_id){
$str = mysqli_real_escape_string($this->conn_id, $str);
}
My solution was to initialize the connection if it is not available.
Change line #315:
if ($this->conn_id === FALSE)
{
$this->initialize();
}
$str = mysqli_real_escape_string($this->conn_id, $str);
I met this problem too.
Wolfgang's solution works well for me.
And if you use codeIgniter, change database config
$db['default']['autoinit'] = TRUE;
can also solve the problem.
I'm using the Google Map API V3 sending it the Lat/Lng and it returns the full address. I'm parsing the address that's returned by using the Object. It works for many addresses but for some of them it is generating the PHP error of about the property being a non-object:
PHP Notice: Trying to get property of non-object in get5.php on line 47
PHP Notice: Trying to get property of non-object in get5.php on line 48
PHP Notice: Trying to get property of non-object in get5.php on line 49
Here are the lines of code for 47-49:
$city_google_api = $country->AdministrativeArea->Locality->LocalityName;
$state_google_api = $country->AdministrativeArea->AdministrativeAreaName;
$zip_code_google_api = $country->AdministrativeArea->Locality->PostalCode->PostalCodeNumber;
I would like to debug this further, but I don't know which record this is causing these messages regarding the property of non-object. Is there a way to trap on the error or check for "property of non-object" so that I can dump the variables? I don't want to dump this for each record because that's too much output. In general, I would like to know if there is a way to trap errors to dump variables? Thanks!
Take:
$city_google_api = $country->AdministrativeArea->Locality->LocalityName;
and temporarily re-write it:
$area = $country->AdministrativeArea;
$locality = $area->Locality;
$city_google_api = $locality->LocalityName;
Do the same for the other three lines and, presto, the line number in the error will tell you precisely where the problem is.
Divide and conquer — your debug technique friend.
You could also program defensively from the start so that the error is not just better reported, but "caught" at runtime:
if (!is_object($country))
throw SomeException();
$area = $country->AdministrativeArea;
if (!is_object($area))
throw SomeException();
$locality = $area->Locality;
if (!is_object($locality))
throw SomeException();
$city_google_api = $locality->LocalityName;
or go further and examine the actual type of each object. This is usually overkill, though — once you have fixed your code, you will know what type each variable has, and the original three lines will suffice.
if (!is_object($country)) {
//debug
}
if (!is_object($country->AdministrativeArea)) {
//debug
}
//etc...
Actually there is not, but you can check if
an object has a certain property using property_exists()
check if it actually is an object using is_object()
or has a certain type using instanceof.
In one of my scripts, I try to do the following
$data[] = self::get($row['sr_id']); // <-- line 55
However, PHP does not allow me to do this, giving me this error
Fatal error: Cannot use [] for reading in /file.php on line 55
The self::get function return either a bool, or an object.
Edit: The get function creates a new object which again loads data from a mysql database.
The solution in my case was this:
Bad line:
$this->$ExtraTag[] = $fullscript;
Good line:
$this->{$ExtraTag}[] = $fullscript;
or
$this->ExtraTag[] = $fullscript;
Old PHP versions accepted $var[] in expressions, allowed reading out the $var content regardless of syntax. PHP 5.1 made that illegal. But sometimes the error is triggered outside of the intented context.
So my guess (again: show more code) is that the preceeding line contains an unfinished expression, to which the $data[] joins.
In case of object attribute you can wrap your $data var into { }, but that doesn't seem to be the problem in your case. (Else there is something in line 54, that you didn't show.) The right hand side can't reasonably trigger the error. Even array accessing [] an integer or object wouldn't trigger that fatal error.
So if nothing helps, just use array_push(). Work around PHP.
The error I got was:
Fatal error: Cannot use [] for reading in
/pathtosite/drupal/sites/all/themes/zenui/templates/page.tpl.php on line 33
Sometime the problem is when you include a line like this:
$page['sidebar_first'][]
This might happen if you are copying a variable name and forgot to comment out the line.
There was two problems:
1. Missing semicolon
2. $variable[] must set a variable
After fixing these two problems my code read:
$page['sidebar_first'][] = $value;
Don't forget to comment out line you are not using to help with the debugging process
Hope this helps fellow programmers like me!
I had same error with following:
echo implode(',', $array[]);
which should have been
echo implode(',', $array);
Hope this can help someone
try:
$data = Array();
$data[] = self::get($row['sr_id']); // <-- line 55
I had the same problem with my script, the following line threw the same error:
$array[]=$value
I simply replaced it by
$array[count($array)-1]=$value
and it worked perfectly.
Another possible problem could be an accidental double ==.
For example accidentally doing $myArray[] == $myNewValue; would cause this error (because you are trying to read a value with the == instead of telling PHP to assign a new array index).