Page 1 of 1
Persistent undefined index error
Posted: Thu Jun 05, 2008 9:12 am
by fluidbyte
I'm simply trying to retrieve a max value from my database, and no matter what I do I get an undefined index error for the "navPosition" (line 14) regardless of if the query returns any results or not. Any ideas what might be causing this?
Code: Select all
$sql_query = "SELECT MAX(navPosition) FROM " . $System["tblPrefix"] . "_navigation WHERE navParent=" . $navParent;
$rs = mysql_query($sql_query);
$row = mysql_fetch_array($rs);
if (!isset($row))
{
$navPosition = 0;
}
else
{
$navPosition = $row["navPosition"];
}
Re: Persistent undefined index error
Posted: Thu Jun 05, 2008 9:17 am
by onion2k
You're not returning navPosition in your SQL, so it's not in the array. MAX(navPosition) is not the same as navPosition.
To fix it, use an alias.. eg MAX(navPosition) AS max_navPosition ... then use max_navPosition as the index in the PHP.
Re: Persistent undefined index error
Posted: Thu Jun 05, 2008 9:19 am
by nowaydown1
To expound on what onion said just a little, you need to provide an alias for your MAX(navPosition). So just switch your query to MAX(navPosition) as `navPosition` or something along those lines and it should work for you then.
Re: Persistent undefined index error
Posted: Thu Jun 05, 2008 9:23 am
by mchaggis
Change your SQL to:
SELECT MAX(navPosition) AS navPosition FROM....
Alternatively try,
Code: Select all
$sql_query = "SELECT MAX(navPosition) FROM " . $System["tblPrefix"] . "_navigation WHERE navParent=" . $navParent;
$rs = mysql_query($sql_query);
$row = mysql_fetch_row($rs);
$navPosition = 0;
if (is_array($row)) {
$navPosition = intval(@array_shift($row));
}
Re: Persistent undefined index error
Posted: Thu Jun 05, 2008 9:35 am
by fluidbyte
lol, thanks. One of those things that after I saw the answer I kicked myself.
Re: Persistent undefined index error
Posted: Thu Jun 05, 2008 9:36 am
by onion2k
Just a personal preference really, but aliasing things to existing column names is a bad idea in my opinion. When your code grows to the point where several people are required to maintain it and the SQL is separated from the PHP (eg stored procedures) it'll stop being obvious what 'navPosition' is ... is it the value from the column? Is it the MAX() value? Is it something else?
It's better to use a logical name that tells the developer exactly what is being returned - max_navPosition is much less ambiguous.