How To Show Data From Database Using PHP CodeIgniter + AngularJS

Hi.. this time I created simple web to show some data from database using PHP CodeIgniter and angularJS. Here is the screenshot of the result page:

page-result

I use MySQL as my db. Here is the table that I’ll use for sample:

books-tbl

First of all, I added some angular javascript files to my js folder. Since I use bootstrap for my csss,I added some bootstrap css too to my css folder. Now we ready for codes 🙂

Model
For books_model, I created function to get all books in getAllBooks() function.

<?
class Books_model extends CI_Model{

	public function __construct()
        {
                parent::__construct();
                $this->load->library('table');
        }

        function getAllBooks(){
		return $this->db->query('select * from books');		
	}

}
?>

Controller
For the controller, I created 2 functions. First function to show the page. Another one to get all books on JSON format.

<?
class Books extends CI_Controller {

    public function index()
    {
        echo 'Hello World!';
    }

    function showbooks(){
    	$this->load->helper('url');
    	$html['title'] = 'List of Our Books';
	$this->load->view('show_book', $html);
	}

    function getAllBooks(){
	$this->load->model('Books_model','booksModel');
	$books = $this->booksModel->getAllBooks();
	$result = $books->result_array();
	$this->output
	   ->set_content_type('application/json')
	   ->set_output(json_encode($result));
		
	return;
    }
}
?>

View

<!DOCTYPE html>
<html>
   <head>
      <?
         echo '<script type="text/javascript" src="'.base_url().'js/angular.js"></script>';
         echo '<script type="text/javascript" src="'.base_url().'js/angular-local-storage.js"></script>';
         echo '<script type="text/javascript" src="'.base_url().'js/angular-strap.min.js"></script>';
         echo '<script type="text/javascript" src="'.base_url().'js/angular-strap.tpl.min.js"></script>';
         echo '<script type="text/javascript" src="'.base_url().'js/transition.js"></script>';
         echo '<script type="text/javascript" src="'.base_url().'js/modal.js"></script>';
         echo '<script type="text/javascript" src="'.base_url().'js/ariestaniablog.js"></script>';
         
         echo '<link href="'.base_url().'css/bootstrap.css" rel="stylesheet"/>';
         echo '<link href="'.base_url().'css/font-awesome.css" rel="stylesheet"/>';
         echo '<link href="'.base_url().'css/custom.css" rel="stylesheet"/>';
         echo '<link href="'.base_url().'css/bootstrap.css" rel="stylesheet">';
         echo '<link href="'.base_url().'css/dataTables.bootstrap.css" rel="stylesheet"/>';
         
         ?>
      <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
      <title>Ariestania's Blog</title>
   </head>
   <body>
      <div id="page-inner" ng-app="mainApp" >
         <div class="row">
            <div class="col-md-12">
               <h2><?=$title?></h2>
               <h5>Love to see you back 🙂 </h5>
            </div>
         </div>
         <hr class="col-md-9">
         <div class="row">
            <div class="col-md-9">
               <!--    Context Classes  -->
               <div class="panel panel-default">
                  <div class="panel-heading">
                     Books
                  </div>
                  <div class="panel-body" ng-controller="toShowBooks">
                     <div class="table-responsive">
                        <table class="table">
                           <thead>
                              <tr>
                                 <th>Book ID</th>
                                 <th>Title</th>
                                 <th>Author</th>
                                 <th>Publisher</th>
                                 <th>Year</th>
                              </tr>
                           </thead>
                           <tbody>
                              <tr ng-repeat="book in bookList" ng-class="$index%2==0?'success':'danger'">
                                 <td>{{book.BookID}}</td>
                                 <td>{{book.Title}}</td>
                                 <td>{{book.Author}}</td>
                                 <td>{{book.Publisher}}</td>
                                 <td>{{book.Year}}</td>
                              </tr>
                           </tbody>
                        </table>
                     </div>
                  </div>
               </div>
               <!--  end  Context Classes  -->
            </div>
         </div>
         <!-- /. ROW  -->
      </div>
   </body>
</html>

Javascript for Angular controller

var showApp = angular.module('mainApp', ['ui.bootstrap.modal', 'ui.bootstrap.transition', 'mgcrea.ngStrap.datepicker', 'mgcrea.ngStrap.timepicker', 'LocalStorageModule']);

showApp.config(function($httpProvider) {
});

showApp.controller('toShowBooks', ['$scope', '$http', function($scope, $http) {

	$scope.showBooks = function(){

        $scope.bookList = null;

        var urlGET = "getAllBooks";
        var config = {headers: {
            'Content-Type': 'application/json'
            }
        };

        var resUrlGet = $http.get(urlGET, {cache: false, transformResponse: function(data, headersGetter) {
                    try {
                        var jsonObject = JSON.parse(data);
                        keepGoing = true;
                        return jsonObject;
                    }
                    catch (e) {
                        console.log(e);
                        $scope.$parent.ResponseMessage = "Error. Cannot Retrieve Data";
                    }
                    return {};
                }});//end ajax 

            resUrlGet.success(function(booksData, status, headers, config) {
                $scope.bookList = booksData;
            });

     };

     $scope.showBooks();

}]);

Hope this simple article can help 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s