I get “undefined variable” PHP notice

百般思念 提交于 2019-12-23 22:31:06

问题


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?


edit

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] => robert@nibbles.com
[email] => robert@nibbles.com
)
Undefined variable: row

回答1:


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.




回答2:


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

print $row[2]

vs

print $row['email];


来源:https://stackoverflow.com/questions/1483002/i-get-undefined-variable-php-notice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!