Thursday, June 23, 2016

Codeigniter tutorial 2

   No comments     
categories: 
CodeIgniter special method

For routing first, the browser looks the controller name then the method name and parameters if available.

In Codeigniter tutorial, we created a function and a function with the parameters.
What if we missed any parameter value in our URL

We get warning and notice about missing argument.

But we can give default values for the parameters;
for example,

hello.php

<?php
class Hello extends CI_Controller{
public function first($p1,$p2="Nimishan"){
echo "This is the first method<br>";
echo "My parameters are : $p1 and $p2";
}
}
?>

here I gave a value 'Nimishan' for the second parameter. and I call the function in URL as below,
localhost/code/index.php/hello/first/blog

So, the output is,



here I call the function only with one parameter, the second parameter is the given value in the php code.

This parameter passing is not a functionality of codeIgnter, It is a functionality of PHP

Create a new function and call that function only.

<?php
class Hello extends CI_Controller{
public function first($p1="Hello", $p2="Nimishan"){
echo "This is the first method<br>";
echo "My parameters are : $p1 , $p2";
}
public function second(){
echo "This is the second method<br>";
}
}
?>

The output with the URL shown below:



What if we have two functions to be shown and we call those functions only with the controller name?
if we type this: localhost/code/index.php/hello
We get 404 error.

We can call the URL only with the controller name by creating a special function called  'index' .

<?php
class Hello extends CI_Controller{
public function index(){
echo "This is a special function";
}
public function first($p1="Hello", $p2="Nimishan"){
echo "This is the first method<br>";
echo "My parameters are : $p1 , $p2";
}
public function second(){
echo "This is the second method<br>";
}
}
?>

Thus the above URL gives no error but this,


therefore we can use this special function to get all the functions without any struggle to call them.

the code:

<?php
class Hello extends CI_Controller{
public function index(){
echo "This is a special function<br><br>";
$this->first();
$this->second();
}
public function first($p1="Hello", $p2="Nimishan"){
echo "This is the first method<br>";
echo "$p1 , $p2<br><br>";
}
public function second(){
echo "This is the second method<br>";
}
}
?>

Here I have used some break tags to show and separate the outputs of each function.



In the output, we have all three methods.

Here the browser found no methods in the URL it looks for the index method.



0 comments:

Post a Comment