I am getting "undefined variable" PHP notification

I am curious why I am getting an error that I did a million times before, but suddenly on some script error I get the error 'Undefined: row'

It seems to me that the line seems 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 pseudo sql ... but I checked this sql expression and I know its outputting the result. I also know that the $ string stores data, because if I go

echo $row[0];

      

I am getting the data I want.

As far as I know, the $ row variable is defined. Nevertheless, it is a mistake. Am I losing my mind or what am I missing here? Should this error / notification only be thrown if $ row doesn't exist?


change

Sorry guys, this is all happening in the inner 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];

}

      


change 2

if i do print_r (string $) i get this:

Array
(
[0] => Robert
[firstName] => Robert
[1] => Nibbles
[lastName] => Nibbles
[2] => robert@nibbles.com
[email] => robert@nibbles.com
)
Undefined variable: row

      

+2


source to share


2 answers


If you don't initialize $row

with anything outside of that if statement, then it's undefined.

Otherwise, if you don't want to initialize $row

to some null value (not entirely unreasonable), you can surround any code that checks $row

outside of the statement if

with something like

if (isset ($ row))
  doSomething ();


This is a pain, but you just have to remember that any variables that you don't explicitly define, even for null, are undefined and can lead to a runtime error if mentioned as an rvalue in your code (except isset

, etc.). In general, either always initialize your variables or just apply the code as above.

I apologize if this is not a problem, but I cannot think of anything more than this without seeing your code.

EDIT: Sorry, it's "isset" not "defined". It has been a while since I was actually working with PHP. I tried to answer the question with concept, not syntax. My mistake.

+8


source


Offtopic, but I recommend using mysql_fetch_assoc () instead of mysql_fetch_array, then you can use actual field names in your code instead of some arbitrary numbers.

print $row[2]

      



against

print $row['email];

      

+1


source







All Articles