【问题标题】:"Notice: Undefined property: stdClass::$id" in php“注意:未定义的属性:stdClass::$id”在 php
【发布时间】:2016-10-03 22:05:03
【问题描述】:

我在以下函数的$uid = $data->id;$uname = $data->username; 行中得到Notice: Undefined property: stdClass::$id

public function userlogin()
{
    $sql = 'select id, username from login_user where email="'.$this->email.'"and password="'.$this->password.'"';
    $result = mysqli_query($this->cn,$sql);
    $numrows = mysqli_num_rows($result);
    if($numrows == 1)
    {
        $data = mysqli_fetch_field($result);
        $uid = $data->id;
        $uname = $data->username;

        $_SESSION['login'] = 1;
        $_SESSION['uid'] = $uid;
        $_SESSION['uname'] = $uname;
        $_SESSION['login_msg'] = 'Login Successfully...';

    }

}

【问题讨论】:

  • 你为什么要调用mysqli_fetch_field函数?
  • mysqli_fetch_field 返回字段定义信息而不是数据。
  • 你应该使用mysqli_fetch_object,而不是mysqli_fetch_field
  • 请了解SQL injection,并考虑如果有人将密码设置为“;drop database;”,您的代码会做什么
  • 永远不要存储纯文本密码!请使用 PHP 的 built-in functions 来处理密码安全问题。如果您使用的 PHP 版本低于 5.5,您可以使用 password_hash() compatibility pack。在散列之前,请确保您 don't escape passwords 或对它们使用任何其他清理机制。这样做会更改密码并导致不必要的额外编码。

标签: php function session


【解决方案1】:

你得到的原因

注意:未定义的属性:stdClass::$id

是因为mysqli_fetch_field 不返回具有id 属性的对象。它用于获取有关列的元信息。您可以在其document page 上查看完整的属性列表。

您可能想使用mysqli_fetch_object

public function userlogin()
{
    $sql = 'select id, username from login_user where email="'.$this->email.'"and password="'.$this->password.'"';
    $result = mysqli_query($this->cn,$sql);
    $numrows = mysqli_num_rows($result);
    if($numrows == 1)
    {

        /* fetch object array */
        while ($data = mysqli_fetch_object($result)) {
          $uid = $data->id;
          $uname = $data->username;
        }

        /* free result set */
        mysqli_free_result($result);

        $_SESSION['login'] = 1;
        $_SESSION['uid'] = $uid;
        $_SESSION['uname'] = $uname;
        $_SESSION['login_msg'] = 'Login Successfully...';

    }

}

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 2011-03-05
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2016-04-17
    • 2015-02-27
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多