?
Solved

Code snippet driving me mad....

Posted on 2011-10-04
23
Medium Priority
?
362 Views
Last Modified: 2012-05-12
HI all,
I have a small bit of PHP code that is driving me mad.

$parent_id is obtained from a value in a database.
The problem is that even when the value is 0 in the database the script doesnt seem to detect it. Ive echoed out parent_id so I know its 0. Ive tried intval($parent_id) but that doesnt seem to work.

If I put $parent_id=0; it works fine. Anyone have an idea of what Im doing wrong?

Here is the code snippet.


            if ($parent_id===0) {
                  return $title;
            } else {
                  dothis($parent_id);
            }
0
Comment
Question by:fox_statton
  • 8
  • 6
  • 3
  • +4
23 Comments
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 36909348
please ensure $parent_id has value 0 or empty.. only then the condition will work properly.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 36909350
You may use trim () or empty() function to check the value then you can use isset()
0
 
LVL 10

Expert Comment

by:ienaxxx
ID: 36909359
... If I put $parent_id=0; it works fine. Anyone have an idea of what Im doing wrong?
it's cause it SETS the value to 0 while checking the ASSIGNMENT operations with "=" ends correctly.

Are you sure the $parent_id is 0 and not, for example, an array?

Try to echo $parent_id right before the check.
Try to print_r($parent_id).

What is the result?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 17

Expert Comment

by:Chris Harte
ID: 36909363
Using triple === is safe type checking. That means the value read from the database has to be an int of value zero, which is different from a char '0'.

Try it with double == and see if that works
0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 36909461
Interesting. According to PHP documentation, intval returns zero on failure. And any string beginning with a zero is treated as an octal number so I guess intval would shift to octal and return a null value for a single zero. But the documentation doesn't mention how it returns a true value of zero even if the string were "00".

Why do you need to convert it? Why not just use $parent_id === '0'?
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36909536
I agree with MunterMan (before I read his post).  

Why are you using === instead of ==?  If there isn't a very good reason, please try ==.  (Even if there's a good read, try == and see if the code works and then we can discuss the reason.)
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 36909615
Please read these two pages to understand the difference between strict identicality with === and loosely typed equality with ==
http://php.net/operators.comparison
http://php.net/manual/en/types.comparisons.php

You can learn about any of your variables with this function.  It prints the type as well as the value.
http://php.net/manual/en/function.var-dump.php

All values returned from the data base are returned as strings.  They may be converted into integers or other data types, either intentionally or accidentally, by PHP type juggling.
http://php.net/manual/en/language.types.type-juggling.php

Hope that helps shed some light on it! ~Ray
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36909788
Ray, that's a good point about the db returning strings.  Pretty concisely identifies the problem.

Hugh
0
 

Author Comment

by:fox_statton
ID: 36910073
I just did the var dump and its showing int(0)

tried changing == to === but still not working.
0
 

Author Comment

by:fox_statton
ID: 36910090
okl, so ive dug a little deeper and found that the match is fine.

It appears for some reason that "return $title" is not returning the variable title

So when I call the function the page using


$sys=dothis($id);
echo $sys;



it shows nothing.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36910129
@fox_statton: Do you know the story about the blind men and the elephant?  We are looking at fragments of information here, and "return $title" is not part of the question.  There could be any number of things wrong.  Maybe you should give us a more comprehensive overview of what you're trying to achieve.  Post the code that is failing and we might be able to tell you how to go about diagnosing and correcting the errors.  Thanks and regards, ~Ray
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36910130
Is there anything in $title?

var_dump ( $title );
0
 

Author Comment

by:fox_statton
ID: 36910146
yes, title is showing string(25)
0
 

Author Comment

by:fox_statton
ID: 36910156
This is what my function looks like:
function find_top_parent($id) {
	$query="SELECT from database etc";

	$result=mysql_query($query);
	$num=mysql_numrows($result); 
	$i=0;

	while ($i < $num) {

		 $title=mysql_result($result,$i,"title");
		 $parent_id=intval(mysql_result($result,$i,"parent_id"));


		if ($parent_id==0) {
		echo "MATCH FOUND $title";
			return $title;
		} else {
		echo "NO MATCH FOUND";
			find_top_parent($parent_id);
		}

		++$i;
	}

}

Open in new window

0
 

Author Comment

by:fox_statton
ID: 36910164
Its a recusive function that Im using to keep searching until it finds parent_id=0

then its supposed to return the title of item with parent_id=0
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36910242
$query="SELECT from database etc";

A statement like this is virtually useless if you want help in debugging.  We really need to see accurate information.

A way to make the query and find the title and parent_id might be something like this code snippet (untested, because I do not have your data base).  I cannot see how you use the $id argument, but maybe you can provide some additional information about that.
function find_top_parent($id) 
{
    $query  = "SELECT parent_id, title FROM mytable WHERE (some clause) ORDER BY parent_id DESC";
    $result = mysql_query($query);
    if (!$result) die("$query" . mysql_error());
    while ($row = mysql_fetch_assoc($result))
    {
        if ($row["parent_id"] == 0)
        {
            return $row["title"];
        }
    }
}

Open in new window

0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 36910296
I may be stating the obvious, but why aren't you letting MySQL do the work and just select the record with parent_id 0?

SELECT * FROM table WHERE parent_id=0

Open in new window


Then you wouldn't need to find it in PHP which is a lot of unnecessary work.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36910312
@xmediaman: If all the SELECT queries go to the same table you may have found the magical answer!  And actually, you would only need to SELECT title from that table.

;-)

~Ray
0
 

Author Comment

by:fox_statton
ID: 36910404
The reason being that each item in the database has a parent (which is another item).

For example:

id | title | parent_id
1 | Tree |0
2| | Branch | 1
3 | Twig | 2
4 | Apple | 3


When the script is called I have only information concerning one item, of example "Apple", so I want to find what the top level parent is for Apple, the item which would have a  parent_id=0

So the function is recursive and works it way through the parents of Apple, until it finds the very top one.



0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36910529
And this is in one table?  Is this by any chance a school assignment?
0
 

Author Comment

by:fox_statton
ID: 36910589
Yep, its in one table. Nope not a school assigment its for a system I built a long time ago, Im sure I did something similar and it worked, but not sure why his code isnt.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36910615
OK, maybe we are making progress.  Can you please post the CREATE TABLE statement and tell us how many rows are in the table.   Also please tell us how many tree structures are embedded within the rows.  Thanks, ~Ray
0
 

Author Comment

by:fox_statton
ID: 36910992
Hi guys,
ok managed to fix it. phew!

It was all down to the recurvie function, had to restructure it, as the variable was not being preserved. I did something similar years ago using arrays, but have obvioulsy lost some of those skillz!

Thanks for all the help.
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this blog post, we’ll look at how using thread_statistics can cause high memory usage.
Recursive SQL is one of the most fascinating and powerful and yet dangerous feature offered in many modern databases today using a Common Table Expression (CTE) first introduced in the ANSI SQL 99 standard. The first implementations of CTE began ap…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses
Course of the Month15 days, 14 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question