【问题标题】:Undefined variable in php but is defined? [closed]php中未定义的变量但已定义? [关闭]
【发布时间】:2013-05-29 08:15:05
【问题描述】:

我想做一个从主页引导的个人资料页面,当我登录并点击个人资料页面时,我有这 2 个错误。我想显示名字和姓氏。

Notice: Undefined variable: first_name in C:\xampp\htdocs\FontLibrary\Profile.php on line 181

 Notice: Undefined variable: last_name in C:\xampp\htdocs\FontLibrary\Profile.php on line 183

但是我已经在 if 语句中定义了?

相关代码是

<?php
            session_start();
            include 'dbfunctions.php';
            $msg = "";
            $id = $_SESSION['id'];
            if (!isset($id)) {
                $id = $_SESSION['id'];
            }

            // Build the SELECT statement
            $select_query = "SELECT * FROM users WHERE id = ".$id;

            //Run the Query
            $result = mysql_query($select_query);

            if ($result) {
                $row = mysql_fetch_array($result);
                $first_name = $row['first_name'];
                $last_name = $row['last_name'];
            }
            ?>

    First Name:<?php echo $first_name ?> <br />
    Last Name:<?php echo $last_name ?> <br />

【问题讨论】:

  • 如果if 条件的计算结果为false 怎么办?
  • 这两个sn-ps甚至在同一个页面上吗?你真的得到了$result吗?
  • 是的,他们在同一个页面上。

标签: php sql variables


【解决方案1】:

var_dump() 你的$result 检查它是否包含你所期望的。

您的查询可能失败(或没有返回任何内容),因此从未设置 $first_name$last_name,因为它会跳过 if 语句。

并且/或者你可以在 if 语句之前初始化它们。

$first_name = "";
$last_name = "";
if ($result) 
{
    $row = mysql_fetch_array($result);
    $first_name = $row['first_name'];
    $last_name = $row['last_name'];
}

附带说明,mysql_ 函数已被弃用。请考虑使用mysqliPDO

【讨论】:

  • 如果这是整个脚本,那么我没有看到任何与数据库的连接代码?如果只是省略了,那么当result 为假时,您可以尝试echo mysql_error(); 来查看错误是什么。
  • 谢谢!我已经找到原因了。因为我在运行查询时没有添加$link。
【解决方案2】:

如果您的结果为假,则未定义变量。您还必须使用默认值在 if 块之外定义它们。

【讨论】:

    【解决方案3】:

    您对mysql_query() 的调用似乎没有返回值。

    if ($result) 为假。

    另外,请转义你传递给数据库的字符串!!! :(

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多