我正在使用codeigniter 2.1.2在WAMP上使用mySql数据库做一个PHP项目,我偶然发现了以下问题:
这是我的模特
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”,这是数据库中的用户名.它显示,但是,我不知道为什么我得到那些错误.希望对此有所帮助.谢谢.
解决方法:
您认为:
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();
}