learner learner - 5 months ago 17
PHP Question

Getting from an id from url in codeigniter

I want to call a function

get
and grab 1 as some value in question controller from following url

http://localhost/project/index.php/question/get/1


The routes config I am trying is:

$route['question'] = 'question_controller';
$route['question/get'] = 'question_controller/get';
$route['question/(:num)'] = 'question_controller/get/$1';


The controller is:

<?php
/**
*
*/
class Question_controller extends CI_Controller
{

function __construct()
{

parent::__construct();
$this->load->helper(array('form'));
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Questions');
}


function get($q_id = null)
{
echo $q_id;
}
}
?>


But, the above url doesn't work at all. I am getting:


404 Page Not Found

The page you requested was not found.


Please help me to solve the issue.

Answer

There is no use adding those routes like that

try this

In Routes

$route['question'] = 'question_controller';
#$route['question/get'] = 'question_controller/get'; // remove
#$route['question/(:num)'] = 'question_controller/get/$1'; // remove

In Controller

function get($q_id = null)
{
    if (!empty($q_id ) && is_int($q_id )) {
        echo "$q_id with the Number";
    } else {
        echo "Its Empty or Its without Number";
    }
}

So when you pass http://localhost/project/index.php/question/get/1 or http://localhost/project/index.php/question/get it will reach same function. It can only reach with the value or without value

Comments