【问题标题】:URI's to fetch database data (CodeIgniter)用于获取数据库数据的 URI (CodeIgniter)
【发布时间】:2012-01-14 08:00:26
【问题描述】:

所以我正在尝试利用 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 错误
严重性:通知
消息:试图获取非对象的属性

【问题讨论】:

  • 显示一些关于如何检索数据的代码以及数据库错误消息

标签: php codeigniter uri


【解决方案1】:

在调用 $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() 会给你返回的行数。

【讨论】:

  • 所以我尝试了这个,但它仍然给了我同样的错误。是因为该函数仍在尝试从控制器中获取一个不存在的值吗?我将如何检查函数以确保不会发生这种情况?
  • @Sneaksta $query->num_rows() 应该足以确保您得到结果。您能否提供有关错误的更多详细信息以及引发错误的原因?
  • 放入一个无效字符会搞砸。我现在只是做了一个简单的函数,它检查输入的字符并确保它们正常,如果不正常则发送一个默认值。
  • 但这仍然不够......这是因为在我的视图文件中,我试图获取由于错误而无法通过的变量。我该怎么做才能防止这种情况发生?
  • 如果问题出在您的视图中,如果没有结果,则在您的模型中返回 false,而在视图中,如果 $question 为 false,则显示错误消息。
【解决方案2】:

调试只是这样做......

    //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();

注意:如果所有这些回显都输出有效值,请检查其他地方是否存在问题

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多