The most requested tutorial for day five of our CodeIgniter screencast series was for an introduction to CRUD operations. We’ll review how to easily create, read, update, and delete records using CI’s active-records class.
Catch Up
- Day 1: Getting Started With the Framework
- Day 2: Database Selecting Methods
- Day 3: Sending Emails
- Day 4: Newsletter Signup
Day 5: CRUD Operations
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.
Tags: Videos



RoyalSlider – Touch-Enable ... only $12.00 
Okay, I’m trying to combine all the daily tutorials into one cms. I stumble upon a conflict while merging lessions 5 and 6. In this lession (day 5) Jeffrey uses this code for retrieving data in his site.php controller:
function index()
{
$data = array();
if($query = $this->site_model->get_records())
{
$data['records'] = $query;
}
$this->load->view(‘options_view’, $data);
}
I.E. he creates a $data array and asigns query results to it.
In the next lession (day 6), Jeffrey uses this code to call corresponding templates:
function index()
{
$data['main_content'] = ‘login_form’;
$this->load->view(‘includes/template’, $data);
}
It turns out that I can not use both methods at the same time because variable $data is used for different purposes in the two of them. How can this be solved? I’ve tried renaming $data in second example and pass it to $this->load->view() as a third parameter:
function index()
{
$qd = array();
if($query = $this->site_model->get_records())
{
$d['records'] = $query;
}
$data['main_content'] = ‘articles’;
$this->load->view(‘includes/template’, $data, $qd);
}
but it’s not working. Can someone please give me a clue about this? Thanks in advance.
@Tomica You’re on the right path, except you switch from $qd to $d and back again to $qd – these should all have the same variable name.
$data is used because it makes sense to the “data” it holds, but you could use anything for a variable name, from $qd to $this_is_the_greatest_variable_ever (though you probably wouldn’t want to type that too often)
Steve thanks for the reply. Unfortunately the inconsistency in the variable name in my previous post was just a typo. The problem occurs, as I assume, because $this->load>view(); does not accept and/or recognize more than two parameterspassed to it. It’s either that or I have another bug somewhere in my code. Simply renaming the two $data variables doesn’t work. And sorry if this all sounds gibberish, I am a total beginner. Can you (or anyone else) please confirm that this would be valid AND execute what I need: $this->load>view(‘includes/template, $data1, $data2);
Sorry for re-posting, I have made another typo there. What I meant was:
$this->load>view(‘includes/template’, $data1, $data2);
I will answer my question. The problem was not in the variable name, because the $data variable was an array, i.e. $data['records'] and $data['main_content'] are two different array members. It is completely safe to use $data. I had a problem on some other place in my code, which I wasn’t able to find. I’ve started the tutorial from scratch and now it’s working flawlessly.
Steve, thank you once again for your help, it did put me on the right trace.
Hi Jeff,
Thanks for this series, I’m starting to use Code Igniter and these screencasts are making it so easy to understand.
One question though, I may have missed something here. But surely using segments to delete rows is really bad practice seeing as someone could quite easily go straight to the url and start deleting rows by changing the number in the uri? Again I may have missed something or it’s me being really naive!
Will
Hey Will,
You are not being naive.
As a beginner I might actually do something like this and leave it as is but it should be noted that we haven’t gone over the login script or any security at this point.
Surely the end result will be that a user has to be logged in to even be able to access the db urls.
As it is now, yes you could just change the number at the end of the url starting at 1 and then go through the numbers until all the records in the db are deleted. I just tried it. You could even write a script to do it automatically for numbers 1 – x as it is right now because it doesn’t error out or throw an exception if the number doesn’t exist.
Hi Jeff, thanks so much for these tutorials.
Very clear and i like the way you explain and it feels really natural the way you code and debug etc.
It gives everyone a the real feel of it.
Now, where can i download these videos?
I saw in one of your comments that you added a link, but it is no where to be found.
Please put it back up.
Thanks
hi Mr.jeff :)
I hope ur doing well !! :)
would u please make a tutorial about codeIgniter and oracle .. or should i say oracle configuration with php in general !!
and we’ll be really grateful ..
Best Regards ;)
I don’t think it’s a good idea to allow deletion via the URL, that and it would make more sense to make the functions of the controller private, especially the ones that call out tasks for the DB.
It gives a nice overview of what CI can do for you though.
First, thank you so much for the tutorials. I seem to be having a problem. The error below is:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1
INSERT INTO `data` (`) VALUES (”)
Filename: C:\xampp\htdocs\ci_CRUD\system\database\DB_driver.php
Line Number: 330
site_model.php
db->get(‘data’); //site_model php model receives ‘data’ from site.php controller
return $query->result(); //site_model does insert query into databse using active records
}
function add_record()
{
$data=”;
$this->db->insert(‘data’, $data);
return;
}
function update_record()
{
$this->db->where(‘id’, 4);
$this->db->update(‘data’, $data);
}
function delete_row()
{
$this->db->where(‘id’, $this->url->segment(3)); //1. controller, 2. method, 3. value, so 3 segments and third segment will be deleted
$this->db->delete(‘data’);
}
}
My codes for update:
View
id”, $record->title); ?>
id); ?>
contents); ?>
No records were returned.
Controller
function update() {
$data = array(
‘id’ => $this->input->post(‘id’),
‘title’ => $this->input->post(‘title’),
‘contents’ => $this->input->post(‘contents’)
);
$this->site_model->update_record($data);
$this->index();
}
Model
function update_record($data) {
$this->db->where(‘id’, $this->uri->segment(3));
$this->db->update(‘data’, $data);
}
However, whenever I try to update a post, it would return the database 0. Could someone guide me so I do it correctly?
A clearer view of the codes: http://codr.cc/e915d0
Jubic,
The segment method used in the delete relies on the segment being set in the h2 tag in the view because it’s a link with the segment appended to the end of the url.
I don’t think you can use that for an update because theirs nothing to tie the anchor to.
I think you would either put in another form like the create form and have the update function query the db for what ever you type in the title field and get the id, and then do the update of the contents for that id.
Or have the view also echo out a update link for each record with the anchor’d segment that takes you to a form to type in the new contents before updating?
I’m not sure which way is best but I know segment won’t work without a link adding that segment to the url like it does with delete.
First, much thanks for all your effort and good work.
Question on the separation of roles in MVC apps. I noticed in this (CRUD) example, there’s a fair amount of PHP logic in the view. I Understand that this is a quick demo and won’t necessarily be as tidy as a commercial app. However, PHP logic interspersed with HTML can confuse a site designer who doesn’t know PHP and may unwittingly screw up the code. Also, PHP, interspersed with HTML, doesn’t look like clean PHP and may be hard to follow. For instance, I noticed that the ‘for’ loop indentation was ragged.
Is there a recommended approach for minimizing the actual PHP displayed in a view, say, by hiding it in funtionc calls? Like:
?
Thanks.
First, much thanks for all your effort and good work.
Question on the separation of roles in MVC apps. I noticed in this (CRUD) example, there’s a fair amount of PHP logic in the view. I Understand that this is a quick demo and won’t necessarily be as tidy as a commercial app. However, PHP logic interspersed with HTML can confuse a site designer who doesn’t know PHP and may unwittingly screw up the code. Also, PHP, interspersed with HTML, doesn’t look like clean PHP and may be hard to follow. For instance, I noticed that the ‘for’ loop indentation was ragged.
Is there a recommended approach for minimizing the actual PHP displayed in a view, say, by hiding it in function calls? Like:
Do a tutourial on php shorthand….cuz i don’t competely understand them.
http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-5-crud/
when trying to play the video it says Advertisment playing but nothing plays and there is no tutorial video.
thoughts?
Hey Jeff,
Actually this video link is dead, can you help us?
Im in love !
Very nice tutorial, but are you going to have one that covers how to build a form where one can pull up an exiting record, edit it and save it OR create a new record? This would truly be very beneficial to complete what is covered here and helpful to us novices!!!
Please!!!!!
Thank you so much for these wonderful tutorials! Great job!
Thanks for these great tuts mate!
By the way I was just thinking about some things ( keep in mind I’m not an expert ;) ):
1) wouldn’t it be better to have the model receive any parameter in the function calls as opposed to extracting them directly from the url… I think it would let you more freedom to choose the ways you want to use your model (eg: pairing it up with a restful api..)
To make it clear:
function delete($id)
{
// stuff here
}
…instead of…
function delete()
{
$this->db->delete($this->uri->segment(3));
}
2) where is the best place to do error checking? controller or model?
Keep on the great work!
Met