-
Home
-
Blogs
-
CodeIgniter-PHP-Framework-Tutorial-3- -
CodeIgniter PHP Framework Tutorial - 3
By Harsh Aggrawal | Jul, 16 2018 07:14
Hi guys this tutorial based on PHP Framework. Today in this tutorial we discuss on how to execute mysql queries using model in CI.
First of all we know the base knowledge of MYSQL queries.
Now we create model, as we discussed earlier How to create model and which directory of CI contains model file.
Following are the steps:-
- Open application->model , now
- Open your text editor Notepad++ or else create now file and write following code : -
class HomeModel extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function index()
{
}
}
- As we already discuss each line of above code in previous tutorial.
- Now we need to work on index() action/method, first of all we get the data from table of database.
- I thing you have already known about database and table formation.
- For ex - we have a Table named Student, and its fields are as follow..
CREATE TABLE table_name( id int auto increment, name varchar(255), email_id varchar(255), PRIMARY KEY( id ) );
- Now create a query in CI..
$this->db->select("*");
$this->db->from("student");
$this->db->order_by("name", "asc");
$query = $this->db->get();
if($query->num_rows()>0) {
return $query->result_array();
}
- The above query help to fetch whole data from student table.
- All data return to controller, and code looks like....
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("HomeModel");
}
public function index()
{
$data["students_list"] = $this->HomeModel->getStudentsList();
}
}
- $data["students_list"] assign a variable in which store data get from model.
- Now display this data on web page... firstly we create view file... in view directory.
- and save it as home.php in application->view directory.
- Now come to controller, now we can pass the data variable to the view, firstly we need to load view file on controller using... $this->load->view("home", $data);
- Now passing the $data variable to view file... some thing looks like...
public function index()
{
$data["students_list"] = $this->HomeModel->getStudentsList();
$this->load->view("home", $data);
}
- Now goto application->config->database as we discuss earlier... check database username, password, database name is corrected.
"hostname" => "localhost",
"username" => "root",
"password" => "",
"database" => "demo",
- Now open browser , then project... Open url http://localhost/CI/home
- if browser window looks like as below...
- Its means your work done successfully.
If your screen looks like as above Image, its means you successfully done your JOB.
I hope you like this tutorial.
On next tutorial we will discuss on how to insert and update database in CodeIgniter.
0 comments