How to Get Records from Database with AngularJS in CodeIgniter 3

Data selection is required either to display information on the screen or use it for some data manipulation.

If you want to get records from the MySQL database using AngularJS in CodeIgniter then you need to create a method in the controller for handling the requests and return a response.

How to Get Records from Database with AngularJS in CodeIgniter 3


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. Download AngularJS
  6. View
  7. Demo
  8. Conclusion

1. Table structure

I am using users table in the demonstration.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(60) NOT NULL,
  `name` varchar(50) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `email` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Navigate to application/config/database.php and define the Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 '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
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

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

3. Model

Create Main_model.php file in application/models/ directory.

Define a single method –

  • getRecords() – Select all records from users table and return the response array.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main_model extends CI_Model {

  function getRecords(){

    // Select user records
    $this->db->select('*');
    $q = $this->db->get('users');
    $results = $q->result_array();

    return $results;
  }

}

4. Controller

Create User.php file in application/controllers/ directory.

Define 3 methods –

  • __construct() – Load url helper and Main_model model.
  • index() – Load user_view view.
  • getUsers() – This method call from the $http service request in AngularJS script.

Call getRecords() method of Main_model to fetch users list and it returns an Array.  Return $data Array in JSON format.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

  public function __construct(){

    parent::__construct();

    // load base_url
    $this->load->helper('url');

    // Load Model
    $this->load->model('Main_model');
  }

  public function index(){

    $this->load->view('user_view');
 
  }

  // Call this method from AngularJS $http request
  public function getUsers(){
    // get data
    $data = $this->Main_model->getRecords();
    echo json_encode($data);
  }

}

5. Download AngularJS

  • Download AngularJS from its Official website.
  • Create assets folder in the project root.
  • Store the downloaded script in assets/ folder.

 


6. View

Create user_view.php file in application/views/ directory.

Include angular.min.js in the <head> section.

Display users list in <table> by looping on users object using ng-repeat directive.

Script

Create a getUsers() method.

Send $http service request to <?= base_url() ?>index.php/User/getUsers and on the successful callback assign response.data in $scope.users object.

Completed Code

<!DOCTYPE html>
<html lang="en">
<head>
 <title>How to Get Records from Database with AngularJS in CodeIgniter 3</title>
 <!-- AngularJS -->
 <script src='<?= base_url() ?>assets/angular.min.js'></script>
</head>
<body ng-app='myapp'>

  <div ng-controller='userCtrl'>
    <!-- User Records -->
    <table border='1' style='border-collapse: collapse;'>
      <thead>
       <tr>
        <th>Username</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
     <tr ng-repeat='user in users'>
       <td>{{ user.username }}</td>
       <td>{{ user.name }}</td>
       <td>{{ user.gender }}</td>
       <td>{{ user.email }}</td>
     </tr>
    </tbody>
  </table>
 </div>

 <!-- Script -->
 <script>
 var fetch = angular.module('myapp', []);

 fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
 
   $scope.getUsers = function(){
    $http({
     method: 'get',
     url: '<?= base_url() ?>index.php/User/getUsers'
    }).then(function successCallback(response) {
      // Assign response to users object
      $scope.users = response.data;
    }); 
   }
   $scope.getUsers();
 }]);

 </script>

</body>
</html>

7. Demo

View Demo


8. Conclusion

Define a method in the controller to get records from the MySQL database and call it from the $http request in the Angular script.

You can also use the CDN link for including the AngularJS script in the view.

If you found this tutorial helpful then don't forget to share.