Continued from Hello World – CodeIgniter!
I’ve been a bit busy with my development works. Talking about codeigniter,i will discuss today on how we can use it to access MySql database, insert data into tables, retrieve and display them, at times delete them. We’ll create a very simple Bookmark Manager App (just for the sake of understanding models in codeigniter, i’ve added code over the last article )
what we’ll do today
-1. if you don’t have codeigniter yet, download it from ci site.
0.rename extracted CodeIgniter zip folder to ci & add it to your server root - xampp/htdocs or wamp/www folder
1. Database Design: create database & table representing our Bookmark Storage requirement & save some configuration setting so that codeigniter recognizes which database we want to work on.
2. Model: describe the database accessing logic (called business logic, it’s where the real business goes, your data will be your business & you’ll build logic over this business) – CRUD – create, retrieve, update, delete actions, in Models of the codeigniter
3. Controller: use the Controller to access data from the Model & pass them to View so that it can display them.
4. View: Create a simple View with HTML forms, that helps user with CRUD operations
5. Test
1. Create Database named ci_test going to http://localhost/phpMyAdmin, click on this database, there are zero tables yet. copy paste the table structure by going to SQL link. and Go.
CREATE TABLE IF NOT EXISTS `bookmarks` (
`bookmark_id` int(11) NOT NULL AUTO_INCREMENT,
`url` varchar(255) NOT NULL,
`description` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`bookmark_id`),
UNIQUE KEY `url` (`url`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
http://localhost/phpMyadmin Interface: Create table from SQL
You created your database & table.
Open application/config/database.php and change as followings
$db['default']['hostname'] = "localhost"; //hostname
$db['default']['username'] = "root"; //default user name in local dev environment
$db['default']['password'] = ""; //default password is blank
$db['default']['database'] = "ci_test"; //our database
$db['default']['dbdriver'] = "mysql"; //we are going to use MySql databaseleave others as default for now. Now you told codeigniter to use our database in the application we are going to build.
2. Defining Model (a PHP class that’ll wrap our relation database model to Object Oriented style)
Here Bookmarks_Model is a PHP class, file name bookmarks_model.php & with some methods inside it inside the Models folder,
filename: Application/Models/bookmarks_model.php
the relation between file name & class name is
classname = ucfirst($filename) without .php extension ok //first letter uppercaseit will look like this
<?php
class Bookmarks_model extends Model {var $url = '';
var $description = '';function Bookmarks_model()
{
// Call the Model constructor
parent::Model();
}
function get_last_ten_entries()
{
$query = $this->db->get('bookmarks', 10);
return $query->result();
}function save($u,$d)
{
$this->url = $u;
$this->description = $d;
$this->db->insert('bookmarks', $this);
}
function delete($id)
{
$this->db->where('bookmark_id', $id);
$this->db->delete('bookmarks');}
function update_entry()
{
$this->url = $_POST['url'];
$this->description = $_POST['desc'];
$this->db->update('bookmarks', $this, array('bookmarks_id' => $_POST['id']));
}}
?>
3. Inside Controller
Here Hello is a PHP class, file name helllo.php & with some methods inside it inside the controller folder. controller & function inside it are the only way user can interact with our system, that’s why we can say controller has control over the flow of the application, we’ll access this controller later as: http://localhost/ci/index.php/hello and each function inside it as – see comment in the code.
The naming convention for filename & class name is
classname = ucfirst($filename) without .php extension
filename: application/controllers/hello.php
<?php
class Hello extends Controller {
function Hello()
{
parent::Controller();
$this->load->database();//load database library
$this->load->model('Bookmarks_model'); //load just defined model
}function index($data='') {
//accessed from url when typed http://localhost/ci/index.php/hello
$bookmarks=$this->Bookmarks_model->get_last_ten_entries();
//call the function inside model which returns last ten entries
$data['bookmarks']=$bookmarks;
//create $data array with the values returned from the model function
$this->load->view("hello_view",$data);
//load the view named hello_view.php passing $data to it.
}function save()
{
//accessed from url when typed http://localhost/ci/index.php/hello/save
//retrieve data from the form post method
$u=$this->input->post('url');
$d=$this->input->post('desc');
//check for validity
if ($u==''&& $d==''){
echo "Invalid, Entry";
}
else{
//if valid data, call the function of the model which will save our data
//to database
$this->Bookmarks_model->save($u,$d);
echo "Thanks, Link Added!";
}
}
function del($id)
{
//del function is receiving data from URL
//accessed from url when typed http://localhost/ci/index.php/hello/___id___
//___id___ is the promary key of the data
//delete data by passing primary key
$this->Bookmarks_model->delete($id);
echo "Thanks, Link Deleted!";
}
}
?>
4. the view
no naming convention for a view. build your own but you should make it easier to link your controller action to view memorable. just remember you’ll load (like used to include) views using filename without extension in controller. if you like extension see user guide for more $this->load->view options.
filename: application/views/hello_view.php
<h1>Bookmark Manager </h1>
//simple php for each loop to iterate throug our data
//remember $bookmarks was passed from the controller as index of the $data variable, which is accessed here as an array of object.
//if you want to view the structure of the $bookmarks array uncomment the line below this.
//print_r($bookmarks);
//initially the array will be blank, but will show it’s structure after you add some data using the form.
<?php foreach($bookmarks as $b) : ?><?php echo $b->description;?><br>
<a target='_blank' href='<?php echo $b->url;?>'><?php echo $b->url;?></a>
<a href='<?php echo base_url() .'hello/del/'. $b->bookmark_id;?>'> Del</a>
<hr>
<?php endforeach; ?>
<br><br>
//html form to help add data to the database//the action of the form is defined as the save method of the hello controller.
// base_url() function gives the root path of this project
//defined in application/config/config.php as
//$config['base_url'] = http://localhost/ci/index.php/;<form method="post" action="<?php echo base_url() .'hello/save'; ?>">
Url:<input type='text' name='url' > <br>
Description:<input type='text' name='desc' > <br>
<input type="submit" value="Add">
</form>
5. Now go test the application you just created.
Let’s memories $data flow in Codeigniter once
Model – to – Controller – to – View flow i.e.
from database to – [ PHP code to/Data Manipulation ] – HTML presentation
1. Go through the user guide, remember this, when you see the terms Model, View & Controller – you just keep focused in the PHP Classes inside the folders named Models, Controllers & Views within the system/application folder of the codeigniter.
Model – PHP files, each file, each class for each table in database or group as you like, application/models,
View – PHP files, each file, presentation for actions(methods/functions) in controller, application/views
Controller - PHP files, each file, each class that control application flow, application/controllers
2. when they say, build a model for your database, think that you are going to create PHP files, each for each table.. etc… with a class with some function to access database (using SQL queries or ORM/object relation mapper or plane SQL) & return these data to controller as array or objects like you used to return 0; in C/C++ main functions.function get_last_ten_entries()
{
//codeigniters default ORM activerecord’s way to retrive data
//produces sql like -- select * from bookmarks limit 10
$query = $this->db->get('bookmarks', 10);
return $query->result();//return data to calling function from controller, returns objects array
}3. When they say access data from the model – you’ll be calling from controller or view a function inside a codeigniter models php file to retrieve data from the database. like this.
//load model like you use to include dbconfig.php or whatever, wherever in controller you need
$this->load->model('Bookmarks_model');
//use the function inside it through the loaded model instance
$bookmarks=$this->Bookmarks_model->get_last_ten_entries(); //an object array
data returned from model is stored invariable $bookmarks
4. when they say, pass data to the view, you’ll be using a simple codeigniter function to pass data to a function which is used to load view (php files inside the views folder).why you accessed data in controller? obviously to display or act upon it: so let’s pass it to view that handles our display system, no data manipulation for now.
//create $data array with the values returned from the model function
$data['bookmarks']=$bookmarks;
//load the view named hello_view.php passing $data to it.
$this->load->view("hello_view",$data);
5. When they say, design/markup a view? you are going to add some PHP files in the Views folder, name it as you like but keep the name in order so that it’ll be easier to reference later which controller is calling which view??//you passed the variable bookmarks from step 3(controller), to step 5 (view) in summary just above. now access it & display it.
<?php
foreach($bookmarks as $b) :?>
echo $b->description;
echo ‘<br>’;
echo $b->url;<hr>
endforeach;
?>
Hope this helps you to start out with CodeIgniter, you are ready to explore on your own now.
Regards.
The multicultural internet community adura scans deftly blends the domains of technology,books, literature, and storytelling to create a unique space for readers and curious minds. The reading experience and the connection between books and technology.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete