所以我正在尝试使用CodeIgniter的URI段功能。我有URI段用作id来从数据库中检索信息。 它工作正常,但我注意到如果我输入一个数据库中不存在的id,它会吐出数据库错误。
如何防止这种情况发生?
型号代码:
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
return $query->row();
在控制器中调用模型:
$question_id = $this->uri->segment(3);
$data['question'] = $this->forum_model->get_question($question_id);
PHP错误:
遇到PHP错误 严重性:通知
消息:尝试获取非对象的属性
答案 0 :(得分:0)
在调用$ query-> row
之前,您需要检查查询是否返回了任何结果这样做的方法是:
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
if($query->num_rows() > 0)
return $query->row();
else
return false;
$ query-> num_rows()将为您提供返回的行数。
答案 1 :(得分:0)
调试就行了......
//if this gives u no result, then thats the problem because it couldnt find the
//$this->uri->segment(3);
$question_id = $this->uri->segment(3);
echo $question_id;
//if this prints out the expected result.
//then you should know that the problem is still somewhere down the code.
$data['question'] = $this->forum_model->get_question($question_id);
var_dump($data['question']);
//this is for your model.
echo $question_id
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
return $query->row();
注意:如果所有这些回声输出有效值,则在其他地方检查问题