Before I proceed to demonstrate how to build a simple view file for displaying the contents of the corresponding “users” MySQL table, first it’s necessary to define the structure of the table in question and to populate it with data about some fictional users. Therefore, based on this requirement, here’s how this sample table would look:
As shown above, this MySQL table is composed of four basic fields, named id, firstname, lastname, and email respectively, which also have been populated with data about some hypothetical users (yes, I can dream of Jennifer Aniston being a user of my application, can't I?). Now that this sample table has been created and filled with basic information, it’s time to define the view file that will display this data on screen. Take a look at it, please: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $header;?></h1> <ul> <?php foreach($users as $user):?> <li> <p><?php echo 'Full Name: '.$user['firstname'].' '.$user['lastname'].' Email: '.$user['email'];?></p> </li> <?php endforeach;?> </ul> <p><?php echo 'Total number of users :'.$numusers;?></p> </body> </html> As shown above, the view file is indeed extremely simple to grasp. In this specific case, the contents of the $data array defined by the controller are automatically turned into PHP variables, and their values are echoed to the browser in the form of an HTML page. Also, it’s worthwhile to note how user data is traversed with a foreach loop, which has been interspersed into the HTML markup. Finally, you must save the view file to the /system/application/views/ folder, and test it by typing the following URL on your browser: http://localhost/codeigniter/index.php/users/ That’s all, trust me. Try out this example with your own web server and you’ll see that it works like a charm. So, are you starting to realize how easy it is to build a database-driven application with Code Igniter? I hope you are! And if you still aren’t convinced about the great functionality of this PHP framework, then use all the code samples included in this tutorial, and start coding your own programs. Fun is already guaranteed! Final thoughts In this second part of the series, you hopefully learned how to develop a basic MySQL-driven application with Code Igniter. As you saw for yourself, the process in actually straightforward and permits to implement very easily the MVC pattern. In the next article, I’m going to teach you how to paginate database records with Code Igniter, so now that you know what to expect from this tutorial, you don’t have any excuses to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|