Sunday, January 28, 2018

Active Records in Codeigniter

What are Active Records ?


Active records are basically the design patterns, which are used for dealing with the databases. Codeigniter package contains a class of ACTIVE RECORDS. This pattern of active record allows its users to insert, select, delete and update etc from database with plus point of minimal scripting. You do not need to write long queries e.g here is query in core PHP 

Select * FROM MyTable Where id = 1;

Now the same query in codeigniter with Active records is:

$this->db->where('id',1)
               ->get('Mytable');

Why use Active Records?

Active records has some of advantages, which are
  • it allows minimal scripting, it shorten the queries
  • Active records allows you to make database independent applications. Manual quries like mentioned above runs only on Mysql . But active records allows you to make database independent applications. Active records can be used in all the database that are supported by codeigniter
  • Active records make your database more secure against sql injections.
  • This can help support a clean separation of concerns and independent development that allows parallel, simultaneous development of application layers.
  • Code reusability
  • Application maintainability

Active record functions:

Well in this post I can not tell you all the functionality in the database class of the codeigniter, but I can tell you the basic ones. You can find all the details in the user guide or documentation of codeigniter which I talked in my first post. Some of the functionalities are:

$this->db->insert();
$this->db->delete();
$this->db->update();
$this->db->select();
$this->db->where();
$this->db->get();
$this->db->limit();

For more functions, visit the documentation of codeigniter. here is the link https://www.codeigniter.com/user_guide/

I hope this post was a help for you, leave your queries in the comments below, God bless you all !

Database in codeigniter !!!!

For using the database in codeigniter, first of all you need to connect your database using the user name, password and host name. In core php, you need a connection of database every time when you want to run database queries, but in codeigniter it is not like that. You have to configure your database for only one time. And it will load automatically every time you run your project. This is done only by loading the database library of codeigniter.

Codeigniter provides the functionality of autoload. The libraries that we want to load frequently in our project, so instead of loading them each time, we will load them in the autoload.php file which resides in the ../application/config/autoload.php in codeigniter.

Database library is the built in library which comes in the codeigniter package. we just need to load it and configure our database.

How to configure our database?

In order to configure our database, go to application folder, then config folder, then click on the database.php file and open it.
At the end of this file you will find a code some thing like this:
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',          //here you have to give your host name
'username' => 'root',                  //here you have to give the username
'password' => '',                         //here you have to give the password. In case of                                                                         localhost, it is null

'database' => 'yourDatabaseName',          //your database name comes here
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

After giving the user name, password and host name. Save it , and your database will be configured and ready to use. Now for using your database and running queries of database you just need to load your database library.

How to load a database library?

There are two ways to do it. One way is to load your database library manually each time when you want to run queries. 

<?php
class MyModel extends CI_Model{

public function fetchingData(){

$this->load->database();

}
}
?>

Now by loading the database library, the db object becomes available, and we can use different operations of database like insert, delete, update and select etc through this object like this:

<?php
class MyModel extends CI_Model{

public function fetchingData(){

$this->load->database();          //loading library manually each time
$this->db->select('myTable');
$this->db->get();

}
public function deleteTable(){

$this->load->database();          //loading library manually each time
$this->db->delete('myTable');
$this->db->get();

}
}
?>

Other way is to load your library in to the autoload.php file for the one time only. It will load automatically every time your application starts. Go to the application folder then to the config folder and then open the autoload.php file. complete path is ../application/config/autoload.php. Their you will find an array of libraries that you want to load automatically. It will be empty because you have not loaded any libraries in autoload array yet. Just load the database library their. like this:

$autoload['libraries'] = array('database');

After loading the library in that array, save the file and close it. Now you don't need to load the database library again. Just use it.

I hope this post was help for you all, leave your queries in the comments, if any ! God bless you all.

Models in Codeigniter ...... MVC pattern !!

As we discussed in the previous post that codeigniter works on the MVC pattern, which is Models, Views and Controllers.
We have discussed in detail about the controllers and the Views in previous posts. Now we are going to discuss about the Models.

Firstly, a question arises here that

What are Models?

Models are most important part of MVC pattern. Models in codeigniter are extended for the parent class of CI_Models. Models are used to write queries in codeigniter. Models directly relates with databases. This parent class CI_Models provides a by default object which is "db". This object is used to access different database operations like select, insert, delete etc. e.g

$this->db->select('myTable');
$this->db->insert('myTable');
$this->db->delete('myTable');

How to create a model?

Models are created simply by creating new file in the Model folder which resides in the application folder of codeigniter and saving that file with .php extention. Keep the first letter of the model name capital. e.g MyModel.php

Every model has a some functions which are called through the accessing the model first and then accessing that function define and declared on the Models.

Every model is loaded first in the controllers, after loading the models, then its function are accessed in that controller.

How to define and declare model?

The code for declaring the model will be something like this. First you have to extend the parent class and create a user defined model class, by giving the same name to the class as you have given the name to file while creating the file in models folder.

The code in the file would be like the one given below:

<?php
class MyModel extends CI_Models{
public function exampleModel(){

echo "hello I am a model";

}
}
?>

 How to load a model in a Controller?

To make the model work and accessed through a controller. we need to load the model first. e.g we have created the model above with the name MyModel.php. Now how we will load this model in the controller that we created in the previous post , here is an example .

<?php class MyController extends CI_Controller {

public function index(){

$this->load->model('MyModel');    //No need to give the extention of model
$this->MyModel->exampleModel();  //function of Model that we created above

}
}
?>
This is how we load the model in controller and access the function of models.
I hope this post was a help for you . leave your queries in the comments. God bless you all !

Saturday, January 27, 2018

Views in codeigniter ... MVC Pattern

As we know, codeigniter works on the MVC pattern, which is Models, Views and Controllers.
We have discussed in detail about the controllers in previous post. Now we are going to discuss about the Views.

First of all we should know that 

What are views in codeigniter ?

Views are considered to be the special files in Codeigniter that are used to store the markup outputted by the applications. Views are consist of HTML and PHP tags. As we all know that HTML is used in front-end designing of websites or any web application. We also know that some of the PHP tags are also used in designing the interfaces of any web application.

A view can be defined as a simple web page, or a page fragment, or any interface of web application with which the end-user is going to interact like header, footer, sidebar or body etc.

How views are created ?

Views can be created by creating a new file  in the views folder which resides in the application folder of codeigniter and saving the file with the .php extension. let say, you have created a file in views folder and saved it with name myView.php. Your View will be created.

The code in the myView.php file is as follow:

<html>
</body>
<h1> This is my View </h1>
<p> I am going to be loaded in the controller that we have created in the previous post </p>
</body>
</html>

How to load Views in Controllers?

The views that we create in the views folder are loaded in controller in order to be displayed on the web. The syntax for loading a view in the controller is as follow:

$this->load->view('myView');

There is no need of giving extention of the file that is .php because codeigniter is an intelligent framework.

Full Code in controller for loading the view:

<?php class MyController extends CI_Controller {
// its the controller that we created in the previous post

public function index(){       // it is the by default function that is called by controller itself
$this->load->view('myView');     // its the view that we have created above
}
}
?>

I hope this would be a help for you. God bless you all. share this post and comment your queries, if any . Thankyou very much

Friday, January 26, 2018

Controllers and its functions in Codeigniter

What is a Controller ?

A Controller is simply a class file that is named in a way that can be associated with a URI. Consider this URI: example.com/index.php/ blog / In the above example,CodeIgniter would attempt to find a controller named blog.php and load it. When a controller's name matches the first segment of a URI, it will be loaded.

As you all know about the URI segments. In codeigniter, the first segment is the name of the controller. The second segment is the name of that controller's method which is being called. And the third segment can b any value that is passed in any method as a parameter. e.g

www.example.com/Mycontroller/method/parameter

Creating a Controller:

You can create a controller simply by opening the controller folder, its path is as follow:

....htdocs/codeigniter/applications/controller

After opening the controller folder, create a new file by giving the name of your choice and save it with a .php extension. Keep the UCfirst approch in naming your controller i.e keep the first letter of your controller's name capital. It is a good practise. e.g Mycontroller.php

After creating your file write the following code in that file. Firstly, to make that file work as a controller, you need to extend the parrent class of controller that is CI_Controller. Here is an example of syntax of declaring and defining a controller class:


This is valid:

<?php class MyController extends CI_Controller {
//name of the class is same as you have given the name to the controller file
}
?>

This is not valid:

<?phpclass myController extends CI_Controller {
//name of the class cannot have first letter in lower case
//class cannot have any other name than the one with which the controller file is saved
}
?>

Creating a Controller's Methods/Functions:
Now, after creating class of controller and extending it from the parent controller class, you can define methods or functions here in the controller. Every controller class calls a by default function that is index(). Here is the syntax to declare and define a method or function in controller e.g
<?phpclass MyController extends CI_Controller {
public function index(){
//default function
echo"I am a by default function";
}
public function myFunction(){
//user defined function
echo"I am a user defined function";
}
}
?>


Codeigniter downloading and installation

Codeigniter Downloading Instruction:

you can download the complete package of codeigniter simply by following the link given below:

https://www.codeigniter.com/

Recently the latest version of codeigniter has been launched that is Codeigniter 3.1.7. You can also get the documentation of codeigniter from the above mentioned link which is a plus point of codeigniter that it has clear and well organized documentation. You can download codeigniter simply by clicking the download button.

Codeigniter Installation Instructions:

CodeIgniter is installed in four steps:

  • Unzip the package.
  • Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  • Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
  • If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
These are the simple steps to install the codeigniter. If your developing on a local server then move the codeigniter folder to your local server htdocs folder.

In the event that you wish to build security by concealing the area of your CodeIgniter documents you can rename the framework and application organizers to something more private. In the event that you do rename them, you should open your principle index.php record and set the $system_path and $application_folder factors at the highest point of the document with the new name you've picked. 

For the best security, both the system}and}any application envelopes ought to be put above web root with the goal that they are not straightforwardly available by means of a program. Of course, .htaccess documents are incorporated into every envelope to help avoid coordinate access, however it is best to expel them from community on the off chance that the web server design changes or doesn't keep the .htaccess. 

On the off chance that you might want to keep your perspectives open it is additionally conceivable to move the perspectives envelope out of your application organizer.
After moving them, open your main index.php file and set the $system_path, $application_folder and $view_folder variables, preferably with a full path, e.g. ‘/www/MyUser/system’.

Thursday, January 25, 2018

Why codeigniter ?

CodeIgniter is an open-source PHP web application structure which can be utilized for quick improvement without the overhead of having to continually construct reusable segments. Giving both an intelligent structure and a reusable interface to libraries written to perform regular errands. The best piece of codeigniter system is that it has an entire and composed documentation.

How codeigniter works ?

Codeigniter uses a MVC pattern. MVC pattern stands for

Models
Views
Controllers

MVC is a product approach that isolates application rationale from introduction. By and by, it allows your website pages to contain negligible scripting since the introduction is separate from the PHP scripting.

The Model represents your data structures. Typically, your model classes will contain functions that help you retrieve, insert and update information in your database.

The View is information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.

The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.