Select records from database for CodeIgniter CRUD
In previous tutorials we learn how to set up out project directory for codeigniter crud.In this we learn how to fetch data from database using MVC of codegniter.
Let's go to our controller i.e. data.php and add some stuff to make CRUD work. Add the some method like the below example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class data extends CI_Controller { function __construct() { parent::__construct(); //load the model $this->load->model('mdl_data'); } // load the view and fetch data from out model function public function index() { $arrData['users'] = $this->mdl_data->getall(); //call the mdl_data getall function to getall data $this->load->view('show',$arrData); // pass all data to view } }
Now let's create out model file which place inside application/model/ name as mdl_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Mdl_data extends CI_Model { function __construct() { parent::__construct(); } function getall(){ $query =$this->db->get('users'); //users is the table name if($query->num_rows()>0){ return $query->result_array(); // this will return all data into array } } }Now let's create our view The results that we have seen we can use them to have Codeigniter CRUD. We just need a view to do it. So a view will look like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CRUD In CodeIgniter</title> <style type="text/css"> .warpper{ width: 100%; } .warpper table{ margin: 50px auto; text-align: center; } .warpper p{ margin: 50px auto; } h1{ text-align: center; } </style> </head> <body> <div class="warpper"> <h1>CRUD In CI</h1> <?php if($this->session->flashdata('success')){ ?> <p style="color:green"><?php echo $this->session->flashdata('success'); ?></p> <?php } ?> <table border=1 cellpadding=5 cellspaceing=5> <tr colspan="6"><td><a href="<?php echo base_url()."data/add/"; ?>">Add New Record</a></td></tr> <tr> <th>Id</th> <th>Name</th> <th>Email Id</th> <th>Edit</th> <th>Delete</th> </tr> <?php if($users) { foreach ($users as $user) { ?> <tr> <td><?php echo $user['id']; ?></td> <td><?php echo $user['name']; ?></td> <td><?php echo $user['email_id']; ?></td> <th><a href="<?php echo base_url()."data/edit/".$user['id']; ?>">Edit</a></th> <th><a href="<?php echo base_url()."data/delete/".$user['id']; ?>">Delete</a></th> </tr> <?php } } ?> </table> </div> </body> </html>
After doing all this run the code like this http://localhost/crud/data/.So a it will look like this:
0 comments:
Post a Comment