我得到“未定义的变量" PHP注意事项 [英] I get "undefined variable" PHP notice

查看:101
本文介绍了我得到“未定义的变量" PHP注意事项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么我在一百万次之前做过的事情会出错,但是突然在某个脚本中遇到了错误未定义的变量:行"

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);

    }

以上是伪sql ...,但是我已经检查了该sql语句,并且知道它带来了结果.我也知道$ row正在存储数据,因为如果我去

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];

我得到了正确的数据.

据我所知,$ row变量已定义.然而,仍然是一个错误.我会失去理智还是在这里想念什么?仅在$ row不存在的情况下才会出现此错误/通知吗?

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?

对不起,一切都发生在if语句内:

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];

}


编辑2


edit 2

如果我执行print_r($ row),则会得到以下信息:

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

推荐答案

如果不将$row初始化为if语句之外的内容,则它是未定义的.

If you don't initialize $row to something outside that if statement, then it's undefined.

否则,如果您不想将$row初始化为某种空值(并非完全不合理),则可能希望将在if语句之外检查$row的所有代码括起来,例如

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();

这很痛苦,但是您要记住,未明确定义的任何变量(甚至为null)都是未定义的,并且如果在代码中被引用为右值,则可能导致运行时错误(在等).因此,总的来说,要么总是初始化变量,要么像上面那样自由地应用代码.

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.

对不起,它是"isset"而不是"defined".自从我实际使用PHP以来已经有一段时间了.我试图用一个概念而不是语法来回答这个问题.我的错.

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.

这篇关于我得到“未定义的变量" PHP注意事项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆