Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database 由URI确定的数据_Database_Codeigniter_Uri - Fatal编程技术网

Database 由URI确定的数据

Database 由URI确定的数据,database,codeigniter,uri,Database,Codeigniter,Uri,所以现在,我的CI网站被格式化为URI的一部分,比如说一个id,然后从数据库中找到一个结果显示在页面上 但是,如果我输入的id不在数据库中,自然会出现数据库错误。有没有更好的方法来保护我的URI不被直接数据库访问?还有,告诉用户他们输入的URL无效的最佳方法是什么?假设您的id存储在$id中。然后您可以这样做 if() // if $id not found - depends how you are doing check { $errorMsg = "Not found";

所以现在,我的CI网站被格式化为URI的一部分,比如说一个id,然后从数据库中找到一个结果显示在页面上


但是,如果我输入的id不在数据库中,自然会出现数据库错误。有没有更好的方法来保护我的URI不被直接数据库访问?还有,告诉用户他们输入的URL无效的最佳方法是什么?

假设您的id存储在$id中。然后您可以这样做

if() // if $id not found - depends how you are doing check
{
    $errorMsg = "Not found";
    $this->session->set_flashdata('errorMsg', $errorMsg );
    redirect('home'); //Redirect to the page which is always available and display flashdata with error message here
}

在我看来,你不仅应该显示一个错误,还应该抛出一个404(或301,取决于你的应用程序),原因是SEO

一个简单的实现:

MY_Controller.php

...
protected function error404()
{

    set_status_header(404);

    $data = array();

    $this->load->view('error404_view', $data);
}
...
        $data = $this->Some_model->get_by_id($id);
        if (empty($data))
        {
            $this->error404();          
        }
        else
        {
            // your view here        
        }
...
examplecontroller.php

...
protected function error404()
{

    set_status_header(404);

    $data = array();

    $this->load->view('error404_view', $data);
}
...
        $data = $this->Some_model->get_by_id($id);
        if (empty($data))
        {
            $this->error404();          
        }
        else
        {
            // your view here        
        }
...

现在,这最好放在我的控制器或我的视图中?这应该放在控制器中。我通常使用flashdata显示消息。它将仅对下一个服务器请求可用,然后自动清除。因此,您可以在重定向到的页面上获取此flashdata,并向那里的用户显示消息。关于flashdata的更多信息在这里-好的,我把它放进去了,我想我需要它来检查数据库中是否有该id。但是,每次检查数据库中是否存在id时,这肯定会很慢吗?最好的方法是什么?另外,我必须为每个控制器功能编写一系列专门的代码。。。。这听起来不太可能。我基本上在一个模型中创建了一个函数来检查页面的id。我将数据库名称传递给该函数,以便它知道在哪里查找,然后重定向到404错误页面。谢谢大家!