if statement evaluates to true on NULL variable when using is_null() - php

So I've got a form with a modal, that modal has 3 rows with 2 text fields each, if the user (me in this prod case) fills out only 2 rows, and leave the other row empty, that 3rd value should be NULL.
In my script I've got:
if (!is_null($_POST['packageDependencies']['bundle'][2])) {
$packageDependency3 = $_POST['packageDependencies']['bundle'][2] . "|" . $_POST['packageDependencies']['version'][2] . "|" . $_POST['packageDependencies']['repository'][2];
$depends = "<key>dependencies</key>
<array>
<string>$packageDependency1</string>
<string>$packageDependency2</string>
<string>$packageDependency3</string>
</array>
";
}
So I'm checking if (!is_null($3rdRow)) { //Do this }, but the variable $_POST['packageDependencies']['bundle'][2] is in fact NULL, as I use var_dump($_POST['packageDependencies']['bundle'][2]); and I get NULL printed to the page, but the if statement is still processing as if it isn't NULL.
$depends gets fwrite() to an XML file, and when I open it, I only see || and but that shouldn't be there as the variable is NULL as I entered no values into those input fields.

Given my advice, a more complete solution would be:
if (!empty(trim($_POST['packageDependencies']['bundle'][2]))) {
NULL is a specific state of a variable that involves the way PHP associates the name of a variable with a variable location. You can think of it like a flag, that indicates a variable name exists, but there is no storage location associated with it. There are a number of situations that empty with trim will catch that will bypass a check against null.

Even though !empty() did the trick, I've decided to use == to be less ambiguous. The answers found here are quite intuitive.
EDIT: As per #gview, adding (!empty(trim($var))) is the best bet as if a user accidentally presses the space key after a tab, it will avoid any errors.

Related

Use a loop to look through POST variables

I'm trying to make a POST method that will receive a value from a table (that is dynamically generated). This value will be equal to a company name, and a hidden field will be there that is equal to company name + "id" appended to it.
Here's my code:
if(isset($_POST))
{
foreach ( $users as $balance_user ) {
if(isset($_POST[$balance_user]))
{
//update user meta with new balance
$newBalance = $_POST[$balance_user];
$postedID = $_POST[$balance_user.'id'];
update_user_meta($postedID, 'balance', $newBalance);
}
}
}
I keep getting the error Illegal offset type in isset or empty. Can I not pass variables in that way? For example if a company is called Acme, and that particularly named input has a value in it, I want to loop through all of the companies in the POST method, and if that part of the loop equals the company passed in the variable, it should do something.
Add these three lines to see the data, as others have indicated, clearly you are assuming some value is in $balance_user which is not there, or is different.
echo '<pre>:';
var_dump($balance_user);
echo ':</pre>';
if(isset($_POST[$balance_user]))
The pre makes it easier to read the debugging output. the :..: will show null values.
Once you run that, you will probably discover that one of your entries in $users is empty.
The output order will show you where that empty user value is.
However:
$postedID = $_POST[$balance_user.'id'];
That could be the error source as well, is there a post value that is. say, $balance_user == fred
fredid
if there isn't, of course you will instantly get that error. You aren't giving the line number of the error so I can't tell which it is, the line number will show it instantly.

Null Value in Database causing undefined index using PHP and MSSQL

I have data that was imported from our mainframe and the last column in the table has null values. (varchar, allow nulls checked. obv.) The field name is all in caps (a result of the mainframe data dump... this is an important clue). When I try to retrieve and echo the data from that field, I get an "UNDEFINED INDEX" error if the field value is Null. If the field has data, I'm fine.
HOWEVER: if i rename the field to something with a lower case letter at the beginning, it works fine, nulls or not.
NOTE: if i put a number at the beginning of the field it doesn't work either.
Trying to find a way around this since I'm dealing with a LOT of tables that are going to get dumped and re-created on an almost daily basis from these mainframe extracts, id rather not have to change the field names. Any help would be GREATLY appreciated!
EDIT: I tried to use "isset" but you cannot check isset on a $XXX->fields('fieldname') line of code. Tried using if(!($XXX->fields('fieldname')) also doesn't work.
In the absence of your ability to use isset(), you can compare if it is exactly NULL with three equals signs (identical operator):
if ( $XXX->fields('fieldname') === NULL ) {
// NULL value, do something else...
} else {
// Not NULL, try something...
}
That doesn't solve your undefined index problem, however. Did you write the class that produces ->fields('fieldname')? If so, or even if not, you can modify the class function fields() to check isset() there and return NULL if not set, or the value if set.
Based on your code in the comments, you might try replacing:
return $this->fields[$this->bind[strtoupper($colname)]];
with:
return ( isset( $this->fields[$this->bind[strtoupper($colname)]] ) ? $this->fields[$this->bind[strtoupper($colname)]] : NULL );
This checks if $this->fields[ ... ] is set, and if so, returns it, and if not, returns null.
But, if that doesn't work, try replacing the same with:
return ( isset( $this->bind[strtoupper($colname)] ) ? $this->fields[$this->bind[strtoupper($colname)]] : NULL );
This checks if $this->bind[ ... ] is set, and if so, returns it, and if not, returns null.

null does not mean it's not set does it? - PHP objects

I have a php object that has a key=>value with something like [ipAddress] = 'NULL'
and if I do:
if(isset($object->ipAddress)){
echo "I am set!!!";
}
It never echoes. because apparently it's not "Set." I was under them impression that it is set, because oft he word NULL.
Is there a away to get around this to say, you are set? with out actually giving it a value? I ask because I attempted to write a function like this: (Don't mind the debugging, its the debugging that lead me to this question)
private function checkForColumnInModelObject($modelObject, $column, $custom_name){
$relationship = array();
foreach($modelObject as $model){
if(isset($model->$column)){
$value_returned = $model->$column;
var_dump($column);
var_dump($custom_name);
var_dump($value_returned);
//$relationship[$custom_name] = $value_returned;
}
}
//return $this->toObj($relationship);
}
So what I am trying to do here is check for a column in a model object. Now you might be given an array of columns, which we walk through in a function that calls this one, and an array of different model objects. were trying to see if the model object has that column.
So for example:
Does equipmentModel have ipAddress Column? yes? fetch me the value.
and the way we do this is by saying "is the column on this model set". The problem is, we might have columns with NULL value ... hypothetically their set, their value is just null, but PHP's isset() is all like NO, you are not set.
Any ideas on how I could write this to keep the same logic, BUT allow values of null to pass through assuming that model has that particular column?
If you want to know if an object property exists, regardless of its value, you can use property_exists.
if (property_exists($model, $column) {
...
}
isset returns true whenever you do an assignment to some variable. When you do $somevar=NULL; (In this case it is an assignment), if(isset($somevar) { echo "Inside"; } , The "Inside" will never print. Since NULL is never considered a value.

Checking for empty attributes while parsing an XML file

A critical function in a PHP script I am debugging get's two attributes from an XML file on an external site. The attributes are labeled 'code' and 'locationCode' within a tag called Channel. The issue is that sometimes the locationCode is posted as an empty string ('') or not defined at all by the site for channels I cannot use, so I need to loop through the channels until I find a non-empty locationCode string. To do this, I created a while loop, but my current implementation does not successfully loop through the location codes. Is there a better way to implement this?
Current code:
public function setChannelAndLocation(){
$channelUrl="http://service.iris.edu/fdsnws/station/1/query?net=".$this->nearestNetworkCode.
"&sta=".$this->nearestStationCode."&starttime=2013-06-07T01:00:00&endtime=".$this->impulseDate.
"&level=channel&format=xml&nodata=404";
$channelXml= file_get_contents($channelUrl);
$channel_table = new SimpleXMLElement($channelXml);
$this->channelUrlTest=$channelUrl;
//FIXME: Check for empty locationCode string
$this->channelCode = $channel_table->Network->Station->Channel[0]['code'];
$this->locationCode = $channel_table->Network->Station->Channel[0]['locationCode'];
$i = 1;
while($this->locationCode=''){
$this->channelCode = $channel_table->Network->Station->Channel[$i]['code'];
$this->locationCode = $channel_table->Network->Station->Channel[$i]['locationCode'];
$i++;
}
}
sample XML file for code: http://service.iris.edu/fdsnws/station/1/query?net=PS&sta=BAG&starttime=2013-06-07T01:00:00&endtime=2013-10-12T18:47:09.5000&level=channel&format=xml&nodata=404
There are two problems I can see with this line:
while($this->locationCode=''){
Firstly, you have typed an assignment (=) when what you wanted was a comparison (==). So instead of testing the condition, this line is over-writing the current value of $this->locationCode and then testing the "truthiness" of '', which evaluates to false, so the while loop never runs.
Secondly, the sample XML file shows that the attribute is not in fact empty, but contains some whitespace. Assuming these are the values you want to ignore (there are none in the sample right now which have any other value), you can use trim() to eliminate the whitespace from the comparison, giving you this:
while( trim($this->locationCode) == '' ) {

Query Based on User Input—PHP

A script I'm using takes in a string of field name/value pairs, splits them, and creates a query from them. The string is formatted like this:
var1==value1,var2==value2...
The values will be submitted by users on the frontend of the website. So, if a user selects a value for var1 and var4 but not 2 and 3 I would need the string to look like this:
var1==value1,var4==value4
Getting the user-submitted data isn't a problem. What is the best way to add in the field name and == only if the associated value is not blank?
if (isset($varname))
isset — Determine if a variable is set and is not NULL
if(empty($varname)))
empty — Determine whether a variable is empty
if(is_null($varname)))
is_null — Finds whether a variable is NULL
In other words, it only returns true when the variable is null. is_null() is the opposite of isset(), except you can use isset() on unknown variables.
You could do something like
$pairs = "var1==stuff,var3==morestuff"
if(strpos($pairs, "var2==") !== false){
$pairs .= "var2==defaultvalue";
}
And you could do that for every var# you want. This would be able to check if the
About the strpos : How do I check if a string contains a specific word in PHP?
Just whip over the submitted form fields looking for anything with a value:
foreach($_POST as $key => $value){
if($value != ''){
// do stuff
}
}
also add a check to skip the submit = submit bit :)

Categories