I'm curious as to why I'm getting an error on something I've done a million times before but am all of a sudden on a certain script getting an error 'Undefined variable: row'
Yet row seems defined to me...
$sql = 'SELECT * FROM table WHERE id="1" LIMIT 1 ';
$res = mysql_query($sql);
if(mysql_num_rows($res) != FALSE) {
$row = mysql_fetch_array($res);
}
The above is pseudo sql... but I've checked that sql statement and I know its bringing out a result. I also know that $row is storing the data because if I go
echo $row[0];
I get the right data.
So to my knowledge, the $row variable is defined. Yet still - an error. Am I losing my mind or what am I missing here? Shouldn't this error/notice only occur if $row didn't exist?
Sorry guys its all happening INSIDE the if statement:
$sql = 'SELECT * FROM table WHERE uID="' . $ID . '" LIMIT 1 ';
$res = mysql_query($sql);
if(mysql_num_rows($res) != FALSE) {
$row = mysql_fetch_array($res);
$firstName = $row[0];
$lastName = $row[1];
$email = $row[2];
}
edit 2
if i do a print_r($row) I get the following:
Array
(
[0] => Robert
[firstName] => Robert
[1] => Nibbles
[lastName] => Nibbles
[2] => [email protected]
[email] => [email protected]
)
Undefined variable: row
If you don't initialize $row
to something outside that if statement, then it's undefined.
Otherwise, if you don't want to initialize $row
to some kind of null value (not entirely unreasonable), you might want to surround any code that checks $row
outside of the if
statement with something like
if (isset($row)) doSomething();
It's a pain, but you've just got to remember that any variables you don't define explicitly, even to null, are undefined and can lead to a runtime error if referenced as an rvalue in code (except in isset
etc.). So in general, either always initialize your variables or liberally apply code like the above.
I apologize if this turns out not to be the issue, but I can't think of anything more than this without seeing your code.
EDIT: Sorry, it's "isset" not "defined". Been a while since I've actualy worked with PHP. I tried to answer the question with a concept, not syntax. My mistake.