A walkthrough of how to build a simple web directory using CodeIgniter and MySQL. The code is available in this . github repo Installation I am assuming you have PHP, MySQL and Apache installed. The easiest way to install all of these is to get which comes packaged with Apache, MySQL and PHP. Or you can try installing each component separately. XAMPP Setting up CodeIgniter is fairly simple, go to their , get the latest version (3.1.11 in my case) and then follow the . Basically all you have to do is unzip the folder into your server’s root which is htdocs for XAMPP or any custom folder if you have installed apache separately. Rename the folder to whatever name you prefer to give, in my case it’s . Don’t get overwhelmed by the lot of files and folders, we will get to them. download page installation instructions bizdir To verify everything is working, go to and you will see a welcome message like this http://localhost/bizdir/ Database Setup Create a database : bizdir bizdir; create database Within that database create a table : directory ( auto_increment primary , business_name ( ) , ( ) , address ( ) , phone ( ), website ( ), email ( ), image ( ) ); create table if not exists directory id int key varchar 255 not null category varchar 255 not null varchar 255 not null varchar 255 varchar 255 varchar 255 varchar 255 Go to application/config/database.php and set up proper configuration for your database by changing the value in array. You will need to add username, password and database. $db[‘default’] $db[ ] = ( => , => , => , => , => , ... ... => ); 'default' array 'dsn' '' 'hostname' 'localhost' 'username' 'php_noob' // <-- your username 'password' 'easy_password' // <-- your password 'database' 'bizdir' // <-- your database 'save_queries' TRUE Here comes the code! As I have already mentioned, CodeIgniter is a MVC framework. So we will have models, views and controllers. In simple terms, models are related to the database, view is the HTML part that you see in the browser and controller is the logic that connects your models with views. The business logic of an application lies in the controller. Model Let’s start by defining our models. Create a file inside application/models and add the following code. Bizdir_model.php { { ->load->database(); } } <?php class Bizdir_model extends CI_Model public function __construct () $this The above lines of code creates a class called Business_model which inherits the class available in CodeIgniter. Then the constructor loads the database so you can use to access the database. CI_Model $this->db Now we need a way to insert and retrieve data. First let’s create a method to get data. get_bizdir() { $query = ->db->get( ); $query->result_array(); } public function get_bizdir () $this 'directory' return The function is pretty much self explanatory. Inside , we are getting all the data present in our directory table. It is equivalent to running the query. Insert some dummy data (restaurants, hotels, banks) into the table via phpmyadmin or MySQL console. get_bizdir SELECT * FROM directory; Controller Next we need to create a controller that loads data from our model and pass it to view. Create a file inside application/controllers and add the following code. Bizdir.php { { ::__construct(); ->load->model( ); ->load->helper( ); } { $data[ ] = ->bizdir_model->get_news(); $data[ ] = ; ->load->view( , $data); ->load->view( , $data); ->load->view( ); } { $data[ ] = ; ->load->view( , $data); } } <?php class Bizdir extends CI_Controller public function __construct () parent $this 'bizdir_model' $this 'url' public function index () 'directories' $this 'title' 'Biz Dir' $this 'templates/header' $this 'bizdir/index' $this 'templates/footer' public function any () 'title' 'Biz Dir: Any Page' $this 'bizdir/any' Just like in model, the controller class inherits the class. Inside the constructor, we are calling the parent’s constructor which is CI_Controller. Then the next line loads the model which makes it accessible as . In the index method, we are fetching all the data and putting it in . CI_Controller $this->bizdir_model $data[‘directories’] After that, another key is added to and the rest is all about passing the variable and rendering the views. The key in the variable will be accessible in our views as and . title $data $data $title $directories The method will act like a default method for any url that is not matched. any() View Now let’s create our views. Create a folder inside application/views and create 2 files: and inside templates. Also create another folder inside application/views and create a file . If you look at your controller, these are exactly the files we are loading there. templates header.php footer.php bizdir index.php application/views/templates/header.php : A complete business directory < > html < > head < > title $title; <?php echo ?> </ > title </ > head < > body < = > h1 style "text-align: center" $title; <?php echo ?> </ > h1 application/views/templates/footer.php <p style= >&copy; Bizdir. All rights reserved.</p> </body> </html> "text-align: center; margin-top: 10px" 2020 application/views/bizdir/index.php <table> <thead> <tr> <th>Business Name</th> <th>Category</th> <th>Address</th> <th>Phone</th> <th>Website</th> </tr> </thead> <tbody> ($business $biz): <tr> <td> $biz[ ]; </td> <td> $biz[ ]; </td> <td> $biz[ ]; </td> <td> $biz[ ]; </td> <td> $biz[ ]; </td> </tr> ; </tbody> </table> <?php foreach as ?> <?php echo 'business_name' ?> <?php echo 'category' ?> <?php echo 'address' ?> <?php echo 'phone' ?> <?php echo 'website' ?> <?php endforeach ?> There is not much going on in header and footer. In the header.php file, we are just printing the title passed from the controller. Inside business/index.php, we are looping through the list of businesses that are in our database. One each iteration, a new is created and all the values are printed inside . <tr> <td> Create another file any.php inside application/views/bizdir and add the following HTML. This is any page Click here to go to home page < = > div style "text-align: center; margin-top: 40px; padding-top: 40px;" < > h2 </ > h2 < > p < = > a href "" </ > a </ > p </ > div Routing Once we have our MVC setup, we need to create routes to see specific views. Open application/config/router.php and scroll to the bottom. Replace the code with the following. $route[ ] = ; $route[ ] = ; $route[ ] = ; 'dir' 'bizdir' 'dir/(:any)' 'bizdir/any' 'default_controller' 'welcome' Here the key of appears in the url and the value on the right points to which method from a controller to call. If only the name of the controller is provided like ‘ ’ in our case, it will call the method by default. Similarly if in the url anything is present after ‘dir/’, it will call the method. You can learn more about . $route bizdir index() any() routing here Now visit . If everything works fine, you will see this. http://localhost/bizdir/index.php/dir As we can see the data are coming through from the database although the design is not something you will be proud of. Let’s fix the page layout and design using the magic of . bootstrap I will be using from and make some customization. Feel free to use any design you like. I won’t go into much detail regarding the HTML and CSS. You can just copy paste the files from and customize as you like if you want to. this layout bootstrap examples github For static files, create a folder inside our root folder i.e. the application and assets folder will be at the same level. assets Open application/config/autoload.php and at the bottom. This will make the function accessible in our views. $autoload[‘helper’] = array(‘url’); base_url() Inside application/views/templates/header.php add the following code right before the closing </head> tag if it is already not there. < = = = /> link rel "stylesheet" type "text/css" href "<?php echo base_url('assets/css/style.css');?>" The function returns the root url. Now open to see your new home page. base_url() http://localhost/bizdir/index.php/dir Now let’s add a functionality to add a new listing to our app. In the top right corner of your home page, you can see “Add Listing” which will link us to the respective page. First we need to add a method in our models that will insert data into the database. The data will be sent from the view and is processed by controller. Open application/models/Bizdir_model.php and inside the model class add a new method . set_bizdir() { $data = ( => ->input->post( ), => ->input->post( ), => ->input->post( ), => ->input->post( ), => ->input->post( ), => ->input->post( ), => ->input->post( ), ); ->db->insert( , $data); } public function set_bizdir () array 'business_name' $this 'name' 'address' $this 'address' 'email' $this 'email' 'phone' $this 'phone' 'website' $this 'website' 'image' $this 'image' 'category' $this 'category' return $this 'directory' The key of the array corresponds to the column of the table in the database. The string inside the post corresponds to the name field in HTML form. Once the values are set, the data is inserted into the directory table. Now we need a method in our controller as well. Open application/Bizdir.php and inside your controller class create a new method add(). { ->load->helper( ); ->load->library( ); ->load->library( ); ->form_validation->set_rules( , , ); ->form_validation->set_rules( , , ); ->form_validation->set_rules( , , ); $data[ ] = ; ( ->input->server( ) == ) { $business_name = ->input->post( ); ( ->form_validation->run() === ) { $business_name = ->input->post( ); ->session->set_flashdata( , . $business_name); ->session->set_flashdata( , ); } { ->bizdir_model->set_bizdir(); ->session->set_flashdata( , $business_name . ); ->session->set_flashdata( , ); } } ->load->view( , $data); ->load->view( , $data); ->load->view( ); } public function add () $this 'form' $this 'form_validation' $this 'session' $this 'name' 'Name' 'required' $this 'address' 'Address' 'required' $this 'category' 'Category' 'required' 'title' 'Add Business' if $this 'REQUEST_METHOD' "POST" $this "name" if $this FALSE $this "name" $this 'message' 'Error adding ' $this 'status' 'danger' else $this $this 'message' ' was successfully added' $this 'status' 'success' $this 'templates/header' $this 'business/add' $this 'templates/footer' The first 3 lines load the required libraries for forms and sessions. We will need sessions to send flash messages to our view. Then rules are set for certain fields. The if block checks if the method is POST i.e. form is submitted. Then it validates the form and based on that create suitable messages. If the form is validated successfully, the data is inserted to our database. Finally, we will render the views. If the request method was GET, nothing inside the if block will be executed. In your application/config/config.php file, add this line at the bottom for our session to work properly. $config[ ] = sys_get_temp_dir(); 'sess_save_path' Finally we need a view where everything will be rendered. Create a new file add.php in application/views/bizdir and add the following code. 'class' 'form-signin' 'bizdir/add' 'message' 'status' &times; Add Business Business Name Address Phone Number Website Email Address Image URL Choose a category Restaurants Hotels Banks Shopping Cafe Add validation_errors(); <?php echo ?> < = > div class "album py-5 bg-light" $attributes = ( <?php array => ); form_open( echo , $attributes); $message = ->session->flashdata( $this ); $status = ->session->flashdata( $this ); ($message) { if ?> < = = > div class "alert alert-<?php echo $status ?> alert-dismissible fade show" role "alert" $message <?php echo ?> < = = = = > button type "button" class "close" data-dismiss "alert" aria-label "Close" < = > span aria-hidden "true" </ > span </ > button </ > div } <?php ?> < = > div class "text-center mb-4" < = > h1 class "h3 mb-4 font-weight-normal display-4" </ > h1 </ > div < = > div class "form-label-group" < = = = = = > input type "text" id "inputName" class "form-control" placeholder "Business Name" name "name" required autofocus < = > label for "inputName" </ > label </ > div < = > div class "form-label-group" < = = = = = > input type "text" id "inputAddress" class "form-control" placeholder "Address" name "address" required < = > label for "inputAddress" </ > label </ > div < = > div class "form-label-group" < = = = = = > input type "text" id "inputPhone" class "form-control" placeholder "Phone Number" name "phone" < = > label for "inputPhone" </ > label </ > div < = > div class "form-label-group" < = = = = = > input type "text" id "inputWebsite" class "form-control" placeholder "Website" name "website" < = > label for "inputWebsite" </ > label </ > div < = > div class "form-label-group" < = = = = = > input type "email" id "inputEmail" class "form-control" placeholder "Email" name "email" < = > label for "inputEmail" </ > label </ > div < = > div class "form-label-group" < = = = = = > input type "text" id "inputImage" class "form-control" placeholder "Image URL" name "image" < = > label for "inputImage" </ > label </ > div < = > div class "form-label-group" < = = > select class "form-control" name "category" required < > option selected disabled </ > option < > option </ > option < > option </ > option < > option </ > option < > option </ > option < > option </ > option </ > select </ > div < = = > button class "btn btn-lg btn-danger btn-block" type "submit" </ > button </ > form </ > div function will print any errors that occurred during form validation. Then the function creates a form with the attributes provided and handles security stuff like CSRF token. The next block of codes checks for any messages and prints them accordingly. Below that we have the HTML with all fields which shouldn’t be hard to understand. validation_errors() form_open() Now refresh your home page and click on “Add Listing” or simply visit this url http://localhost/bizdir/index.php/a dd You will see a nicely rendered form as in the image below. Now go ahead and add data via the form. Remember we have added rules for 3 fields: name, address and category as required. Once the data is added, you will see a message saying if it was successfully added or not. If successfull, go to your home page and you will be able to see the listing. At this point we have created a simple 2 page website to view and insert data. What next? You can add a lot more functionality to this app. To start with, a simple search function would be great. Beside that, you can add features to delete and update listings. Possibly add a login/registration system that allows only authenticated users to add, delete and update the data. I hope this article will be a good point for you to get started with CodeIgniter. Additional Resources Github Repository: https://github.com/sagunsh/bizdir Official CodeIgniter Website: https://codeigniter.com/ XAMPP: https://www.apachefriends.org/index.html Getting Started: https://codeigniter.com/user_guide/tutorial/index.html
Share Your Thoughts