Simplexml issue Can't get Null from empty attribute - php

Hi Guys Hope you can Help:
I am trying to read the xml that is part of a sports scheduling program.
I have Below a Sample of the XML I am reading. So far using Simpmle XML I have been able to read all attributes of a game correctly. However in The example you can see that homescore and awayscore will only show as "" until a score is entered. This is great because I want to put a simple if statement saying if score is null echo "-". This way the viewer knows they are yet to play.
<Fixture Id="404" FixtureName="Round 4" ResourceId="4" PlayingAreaName="Court C" VenueId="2" VenueName="Adelaide Indoor Sports Centre" MapLink="" HomeTeamId="212" HomeTeam="THE SHINERS" HomeTeamScore="29" HomeTeamForfeit="False" AwayTeamId="203" AwayTeam="SANDBAR WARRIORS" AwayTeamScore="8" AwayTeamForfeit="False" Duration="40" Umpires="" CrossLeague="False" DivisionName="Division 1" CalendarColour="FFFF00" ResourceOrder="3" DateTime="13/03/2012 21:20"/>
<Fixture Id="406" FixtureName="Round 4" ResourceId="5" PlayingAreaName="Court D" VenueId="2" VenueName="Adelaide Indoor Sports Centre" MapLink="" HomeTeamId="210" HomeTeam="WE THOUGHT IT WAS A DISCO" HomeTeamScore="" HomeTeamForfeit="False" AwayTeamId="206" AwayTeam="AVERAGE JOE'S" AwayTeamScore="" AwayTeamForfeit="False" Duration="40" Umpires="" CrossLeague="False" DivisionName="" CalendarColour="FFFF00" ResourceOrder="4" DateTime="13/03/2012 21:20"/>
But The "" (empty attribute) always returns zero. Any Tips? I'm relatively new to php

You could use the empty() function.
if (empty($fixture['HomeTeamScore'])) {
echo "-";
}
PHP: empty - Manual

If I understand you correctly, you want to distinguish between "" and "0". Because PHP tries as hard as it can to guess what types you're comparing, statements like $foo == 0 and $foo == '' won't do this, as it will guess that you want to compare numbers, and treat "" as 0.
There are a couple of ways to deal with this:
use the === operator instead of == (or !== instead of !=) (see http://uk3.php.net/manual/en/language.operators.comparison.php)
check the length of the string using strlen to see if it is empty
check the type of the variable using is_int, is_string, etc - this one probably won't work if you've grabbed the values out of SimpleXML, which returns its own types
Since you're using SimpleXML, I would imagine the code would look something like:
if ( (string)$fixture['HomeTeamScore'] === '' )
{
echo '-';
}
else
{
echo (string)$fixture['HomeTeamScore'];
}

Related

How to add integers to a PHP variable

I'm trying to create a sorting algorithm based off a query. Essentially the user would input values for Height, Weight, and a few other attributes. I am then querying our database of models to match that person with someone who has the closest measurements to those that the user inputted. I'm trying to do this based off a weighted variable that I am assigning within the "while" statement of the query and then returning that variable's value at the end. Here is some code to show you what I mean:
$userHeight=$_POST['height'];
$userWeight=$_POST['weight'];
$userShoulder=$_POST['shoulder'];
$userWaist=$_POST['waist'];
$userInseam=$_POST['inseam'];
$heightMatchMultiple=0;
$heightMatchMultiple=0;
$weightMatchMultiple=0;
$shoulderMatchMultiple=0;
$waistMatchMultiple=0;
$inseamMatchMultiple=0;
function matchValues($array){
if(mysqli_num_rows($array) > 0) {
while($row=mysqli_fetch_array($array)){
$heightMatchMultiple=0;
if(isset($row['modelHeight'])){
if($userHeight==$row['modelHeight']){
$heightMatchMultiple=10;
}
elseif($userHeight==$row['modelHeight']+1 || $userHeight==$row['modelHeight']-1){
$heightMatchMultiple=9;
}
elseif($userHeight==$row['modelHeight']+2 || $userHeight==$row['modelHeight']-2){
$heightMatchMultiple=8;
}
elseif($userHeight==$row['modelHeight']+3 || $userHeight==$row['modelHeight']-3){
$heightMatchMultiple=7;
}
else{
$heightMatchMultiple=1;
}
}
echo "Model Match Multiple: " . $heightMatchMultiple . "<br>";
}
}//end of if num rows
else {
echo "No results to display.";
}
}//end of function
When I run this function, it is returning the else statement's value for heightMatchMultiple of 1 instead of 10 because there is a model in the database with a height of 69 which is what I used as user input.
Can I add +1 or +2 directly to the $row['modelHeight'] variable as I did or is there a better way to do this.
EDIT:
Some people were asking where I initialized the variable $userHeight so i added it to the code. I tried creating global variables for $heightMatchMultiple=0 as a way to make those variables usable within my matchValues function. Is this correct?
Where is $userHeight being initialized/passed in? I think the reason you're currently getting 69 is because $userHeight has not been set, hence it gets a value of zero by default, which means that 1 will be the correct answer if $row['modelHeight'] is 69.
To answer your real question, which is really about order of operations: yes, what you have written should do what I believe you are trying to achieve. However, you should probably add parenthesis, even though they aren't strictly necessary, just as a hint to your future self that you really did intend for the calculations to happen in a certain order.
For example, instead of this:
elseif($userHeight == $row[ 'modelHeight' ] + 1 || $userHeight == $row[ 'modelHeight' ] - 1)
you could write this:
elseif(($userHeight == ( $row[ 'modelHeight' ] + 1 )) || ( $userHeight == ( $row[ 'modelHeight' ] - 1)))
Or you could re-write each of the checks using abs() like this:
elseif(abs($userHeight - $row['modelHeight']) == 1 )
This is arguably more descriptive, since what you're really trying to say is "if the difference is 1".
But yes, you can use the + 1 and +2 etc as in your original code, but you do need to set or pass in the $userHeight variable at some point.

Is there anything wrong with the strpos implementation in below case?

I've a variable which contains comma separated strings. This is generated dynamically from the array elements by using implode() function.So sometimes it contains nothing, sometimes it contains 1/2/3/4 strings separated by comma. I want to check whether the stirng Other is present within this comma separated string and if it's present then do the commands written inside if. But I'm facing a issue in which it's never detecting the string "Other" inside the comma separated values though tit's present. Can anyone help me in this regard please?
For your reference following is my code:
$form_data['que_issue'] = implode(",", $request['que_issue']);
if(strpos($form_data['que_issue'],"Other")) {
echo "In If";
die;
if(!$this->mValidator->validate($form_data['que_issue_comment'], "required", "true"))
$this->mValidator->push_error($errors_msgs['que_issue_comment_blank'], 'que_issue_comment');
elseif(!$this->mValidator->validate($form_data['que_issue_comment'], 'maxlength', '100'))
this->mValidator->push_error($errors_msgs['que_issue_comment_length_invalid'], 'que_issue_comment');
} else
echo "In a else";
die;//Its always going in else part only
Thanks in advance.
strpos will return 0 if string match at the begin of the string. But 0 is interpreted as false by PHP.
Always look the documentation and see what is the specific return type/value when the method "fail" and compare against that. In this case
if(strpos($form_data['que_issue'],"Other") !== false)
you should try something like this
if (strpos($form_data['que_issue'],'Other') !== false) {

Detect null column value in PHP mysqli

I have a php project that uses mysqli to query a database. Some of the columns in this database can be null. I have code that looks something like this:
$query = "...";
$result = $DB->query($query);
$row = $result->fetch_assoc();
$column = $row['mycolumn'];
If mycolumn is null, the value of $column appears to be the string, "NULL" (NOT the null value, but actually the string containing the word "NULL"). So what happens if I have columns which actually have the string "NULL" in them? How can I differentiate?
Thanks!
Josh
EDIT:
Upon closer inspection, it appears that the string is actually a 5-characters string. The first 4 characters are "NULL", but the last character is 0x0d, the carriage return. This makes it a lot easier to detect, although I'm still curious if there's a less hack-y way than just doing string comparison.
Use an if condition to check with ===
if($row['mycolumn'] === null) {
echo 'Real Null';
} elseif($row['mycolumn'] == '') {
echo 'Blank';
}
You are looking wrong way. Instead of trying to detect wrong NULL value you have to find out why it is wrong and correct it.
Neither Mysql nor mysqli would return a literal string 'NULL' for a null value.
So, you need to find your own code which converts NULL value to "NULL\n" string either at writing or reading. Are you using raw mysqli as $DB or it's a sort of abstraction class? If so - I'd say problem is there.
After that you can easily read NULL value with strict comparison === as suggested in other answers (though I am not sure about libmysql installations).
seems the column have the data type as string.
If it is string,
we can check by following
if($row['mycolumn'] == '' || is_null($row['mycolumn']))
{
echo "Coulmn is NULL value";
}
else if($row['mycolumn'] == "NULL")
{
echo "Coulmn is NULL value as string";
}

Is it possible to change data type inside a SimpleXMLElement object with PHP?

I have this object
$data = simplexml_load_string('<xml><admin>0</admin></xml>');
where $data->admin = "0" (string). So with a string 0, the following would always return true
if($data->admin) {
echo 'is admin';
}
By casting the variable, this would work correctly
if((int)$data->admin) {
echo 'is admin';
}
But I'm still wondering if it's possible to change the data type inside the object (like doing so inside an array) so I don't have to do type casting.
Not with SimpleXML. What you can do is use DOMDocument instead. Using SimpleXML isn't recommended.
If string is '0' it will return false. If you cast it to int it will still return false. ) And at the end logical expressions are cast to boolean. So what you trying to do is useless)
there is no way to do so in PHP, instead of typecast it you could just try this solution
if ($data->admin != 0){
//is admin
}
You can also try this) Though I don't think its good way) The best here is compare again zero and not to make typecasting. If you want typecasting you can do following. But its not good practice to make 3 operations instead of 1 )
$data = simplexml_load_string('<xml><admin>0</admin></xml>');
if(strip_tags($data->admin->asXML()))
{
//is admin
}

Php test empty string

I have a bit of php code that I'm not understanding why it is acting as it is. I have a variable called contactId that I want to test to see if it is empty. However even if it is empty it evaluates to true. Code is below. Thanks in advance.
print "*".$contactId."*<br/>";
if($contactId != '')
{
//queryContact($contactId);
print "Contact Present<br/>";
}
result returned to screen is:
**
Contact Present
If you want to see exactly what your string is, simply use var_dump(), like this, for instance:
var_dump($contactId)
instead of
print "*".$contactId."*<br/>";
Couple of things you can try:
if (!empty($contactId)) {
// I have a contact Id
}
// Or
if (strlen($contactId) > 0) {
// I have a contact id
}
In my experience I have often used the latter of the two solutions because there have been instances where I would expect a variable to have the value of 0, which is valid in some contexts. For example, if I have a drink search site and want to indicate if an ingredient is non-alcoholic I would assign it a value of 0 (i.e. IngredientId = 7, Alcoholic = 0).
Do it with if (isset($contactId)) {}.
You likely want:
if (strlen($contactId))
You'll want to learn the difference between '' and null, and between == and ===. See here: http://php.net/manual/en/language.operators.comparison.php
and here: http://us3.php.net/manual/en/language.types.null.php
In future, use if(!empty($str)) { echo "string is not empty"}.

Categories