Avatar of fox_statton
fox_statton

asked on 

Code snippet driving me mad....

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);
            }
PHPMySQL Server

Avatar of undefined
Last Comment
fox_statton
Avatar of Loganathan Natarajan
Loganathan Natarajan
Flag of India image

please ensure $parent_id has value 0 or empty.. only then the condition will work properly.
You may use trim () or empty() function to check the value then you can use isset()
Avatar of ienaxxx
ienaxxx
Flag of Italy image

... 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?
Avatar of Chris Harte
Chris Harte
Flag of United Kingdom of Great Britain and Northern Ireland image

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
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

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'?
Avatar of Hugh McCurdy
Hugh McCurdy
Flag of United States of America image

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.)
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Hugh McCurdy
Hugh McCurdy
Flag of United States of America image

Ray, that's a good point about the db returning strings.  Pretty concisely identifies the problem.

Hugh
Avatar of fox_statton
fox_statton

ASKER

I just did the var dump and its showing int(0)

tried changing == to === but still not working.
Avatar of fox_statton
fox_statton

ASKER

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.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

@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
Avatar of Hugh McCurdy
Hugh McCurdy
Flag of United States of America image

Is there anything in $title?

var_dump ( $title );
Avatar of fox_statton
fox_statton

ASKER

yes, title is showing string(25)
Avatar of fox_statton
fox_statton

ASKER

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

Avatar of fox_statton
fox_statton

ASKER

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
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

$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

Avatar of Kim Walker
Kim Walker
Flag of United States of America image

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.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

@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
Avatar of fox_statton
fox_statton

ASKER

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.



Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

And this is in one table?  Is this by any chance a school assignment?
Avatar of fox_statton
fox_statton

ASKER

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.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

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
Avatar of fox_statton
fox_statton

ASKER

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.
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo