3

我正在使用 codeigniter 2.1.2 做一个 PHP 项目,在 WAMP 上使用 mySql 数据库,我偶然发现了以下问题:

这是我的模型

function loadUserData() {
    $sql = "SELECT username FROM user WHERE username = ?";
    $query = $this -> db -> query($sql, $this->session->userdata('username'));

    if ($query -> num_rows() > 0) {
        foreach ($query->result() as $row) {
            $data = $row;
        }
        return $data;
    }

}

控制器

function profile_access() {
    if ($this -> session -> userdata('is_logged_in')) {
        $this->load-> model('profile_model');
        $uData['rows']=$this->profile_model->loadUserData();
        $this->load->view('profile_view',$uData);

    } else {
        echo "<script type=\"text/javascript\"> alert(\"You need to provide your credentials first.\");</script>";
        redirect('login_controller/index');
    }
}

和视图

<?php
      foreach($rows as $r){
              echo print_r($r);
              echo $r[username]->username; //line no. 81 in my code
            }
?>

print_r($r)视图给我以下错误:

alphaomega1
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant username - assumed 'username'
Filename: views/profile_view.php
Line Number: 81


A PHP Error was encountered
Severity: Warning
Message: Illegal string offset 'username'
Filename: views/profile_view.php
Line Number: 81


A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/profile_view.php
Line Number: 81

我希望上面的代码只返回数据库中的用户名“alphaomega”。但是会显示它,但我不知道为什么会出现这些错误。将不胜感激一些帮助。谢谢。

4

1 回答 1

3

在您看来:

foreach($rows as $r){
     echo $r->username;
}

在您的模型中:

function loadUserData() {
    $sql = "SELECT username FROM user WHERE username = ?";
    $query = $this->db->query($sql, $this->session->userdata('username'));

    return $query->result();
}
于 2012-08-20T09:44:00.100 回答