用于获取数据库数据的 URI (CodeIgniter)
所以我尝试利用 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 错误
严重性:通知
消息:尝试获取非对象的属性
So I'm trying to utilise CodeIgniter's URI segment functionality. I have the URI segments being used as ids to retrieve information from the database.
It's working fine, but I have noticed that if I put in an id that doesn't exist in the database, it spits out a database error.
How do I prevent this from happening?
Model Code:
$query = $this->db->select('*')
->from('questions')
->where('questions.id', $question_id)
->join('users', 'users.id = questions.user_id')
->get();
return $query->row();
Call to model in controller:
$question_id = $this->uri->segment(3);
$data['question'] = $this->forum_model->get_question($question_id);
PHP error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在调用 $query->row 之前,您需要检查查询是否返回任何结果。
方法是:
$query->num_rows() 将为您提供返回的行数。
You need to check if the query returned any results before calling $query->row
The way to do it is:
$query->num_rows() will give you the number of rows returned.
要调试,只需执行此操作...
注意:如果所有这些回显都输出有效值,则检查其他地方是否存在问题
to debug just do this...
NOTE: if all this echos outputs valid values, then check somewhere else for the problem