我正在使用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”,这是数据库中的用户名。然而它显示,但我不知道为什么我得到这些错误。我将不胜感激。感谢。
答案 0 :(得分: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();
}