CodeIgniter Forums
no segment, how redirect 404 ? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: no segment, how redirect 404 ? (/showthread.php?tid=64269)



no segment, how redirect 404 ? - stat - 02-02-2016

Hi everyone,

I searched my answers on this forum and google, but no success. 
I have a simply route like : customer/card/1 but if i try it with a wrong id like : customer/card/19999999 i have php error. So i would like to redirect to 404 page if ID doesn't exist but how can I do it ?

Thanks a lot for your answer and your help.


RE: no segment, how redirect 404 ? - abdullacool04 - 02-02-2016

Your project routes never know about 19999999 is in your project(database).
So all you have to do is catch those with controller

In customer Controller


Code:
    public function card($value)
    {
        # then here write an select Query
        #ex
        $result = $this->model_name->check_value($value);
        if ($result == false) {
            # Show 404 page. I you have created custom page in view, Then use load->view().
            # If not use default
            show_404();
        }
        else{
            # Continue with your rest of code
        }
    }


In Model

Code:
    public function check_value($value)
    {
        $query = $this->db->query("SELECT * FROM table_name WHERE filed = $value ");
        $result = $query->result_array();

        $count = count($result);

        if (empty($count)) {
            return false;
        }
        else{
            return true;
        }        
    }



RE: no segment, how redirect 404 ? - stat - 02-03-2016

Ok I understand now. Thanks a lot for your help Aabdullacool04.


RE: no segment, how redirect 404 ? - Diederik - 02-03-2016

Be sure to properly validate your input! Although you process a _GET variable which should be validated by the permitted_ui_chars in your config but if by some fuck-up gets changed to allow all chars you are in trouble.

In this case I would simply type cast the $value to an integer. Or use query bindings to escape the value in your query like in the example below.

Also if you are just interested in knowing if a record with some field value exists, dont't use "select *", but "select 1".

PHP Code:
public function check_value($value)
 
   {
 
       $sql    "SELECT 1 FROM table_name WHERE field = ? ";
 
       $query  $this->db->query($sql, array($value) );

 
       $result $query->result_array();

 
       if (empty($result)) {
 
           return false;
 
       }

 
       return true;