Try Tuts+ Premium, Get Cash Back!
CodeIgniter From Scratch: Day 5
videos

CodeIgniter From Scratch: Day 5 – CRUD

This entry is part 5 of 17 in the CodeIgniter From Scratch Session
« PreviousNext »

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 5: CRUD Operations


Tags: Videos
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • mike

    great course .. one question..when I use $this->index(); to return to the options_view page i get an error – 404 page not found
    the url is http://localhost/ci/index.php/index.php/site/create
    i.e. index.php is repeated thus causing the error
    why has that happened?

    • Dave

      I am getting the same error and cannot update records because I keep getting 404 page not found errors.

      • Matt

        Check your base_url in th config.php in the config folder. Sounds to me like you guys might have index.php in the base url so when you reload with that function it’s writing it twice.

  • http://shorthandlogic.com Joe

    Great tutorial!

    I’ve made it about halfway through to where you’re initially testing your submission form, but on my copy nothing happens when I press submit. CodeIgniter is something new to me so it’s probably something quite silly…

    I’m running MAMP on OS X 10.6 with PHP 5.

    Thanks in advance for your help.

  • http://shorthandlogic.com Joe

    In regards to my last comment: it also seems that some portion of my form is working because, even though the form is not reloaded without any data in it, I see entries have been added to the database with 0′s in the fields.

    • Bob

      You’re not the first person in the comments section to mention the “0′s in the table fields” problem, but no one has addressed it correctly yet.

      The zeros are caused if you load “index.php/site/create” directly into your browser, instead of just “index.php/site”. Since the create() function that gets called when you load “index.php/site/create” is written to load data into the database, and since you’re accessing “index.php/site/create” directly, the create() function loads null values (i.e., zeros) into the database.

      Hope this helps.

      • http://www.litflwebsitedesigner.com Tom

        How do you prevent the create() function from loading twice? is there a way to prevent functions being loaded automatically?

    • JJ

      With regard to the 0′s in the DB, – shot in the dark here….

      I noticed that I had 0′s initially, but checking this out I found that the “data” database table from previous example (blog, I think) had a field called “contents”, but in this example the field is called “content”.

      I’m not sure if this is a fix, – but as I did initially have 0′s, but subsequently this fixed, it might be the reason.

      • http://www.example.com krauses

        If you’re getting 0′s in your row for either title or content, make sure you have your table set up correctly.

        You might being seeing those zeros either because you have the row set to INT instead of CHAR or VARCHAR. It might also be that you have not set the NOT NULL value on that row.

  • http://deviantstudio.ca Richard

    Wish I could find a downloadable version of this one like the others in podcast format. These tutorials have helped a lot.

  • http://www.gordoniihoodia.net penis enlargement

    Well i mostly see this kind of things in all blogs that peoples are always commenting about different matters and topics instead of the topic they are on to, so this kind of things really makes me upset, because i always expecting to spread conversation at this kind of blogs and forum for improves my knowledge base. http://www.Gordoniihoodia.net

    • http://gabrieljones.com Gabriel

      So wait, are you saying CodeIgniter will enlarge your penis? Funny, I heard the same thing, I’m glad you’re spreading conversation at this kind of blogs.

  • alex

    reading up on codeigniter, as i am planning to use it for a project.

    I do have a question about SEO url’s and CI vs CI use of controller/method/etc
    How do we get the best SEO url’s???

  • adhie

    I can’t play for this Day 5. Please help to advise? Thanks

  • http://monkeysarebetter.com mnkysrbtr

    This is awesome thank you so much, really cleared a lot of things up with CI

  • Frank

    Your tutorials helped me get up to speed on Codeigniter.
    I would like to see a tutorial on Codeigniter Shoppingcart when displaying items in a list and allowing users to add to cart.

  • http://www.radiart.pl Radi

    Thx Very Good Work!

  • T_Wrecks

    HEY JW,

    Great screencasts, I subscibe via itunes but this is the only video not in the feed. Can you PLEASE add this to the video to the itunes feed?

    Thanks

  • Goob

    You could really do with a proper IDE or some plug-ins for TextMate. It’s painful to watch someone have to type closing html tags! Oh, and cut down on the coffee. You probably hit the backspace key as much as all the others combined.

    All criticisms over with….I really love this series. I’m learning a lot. I hope there is an advanced course to come. Keep up the good work. And maybe change to drinking apple juice or something ;)

  • adelle

    This Tutorial is What i needed exactly .. But The sound quality is not that good today .. Thanks Very Much ..

  • Michael

    Loving the series so far!

    However, I’d like to know how do I get my update to work?
    Basically so it’s like my create script, but just updates a single entry.

    And how do I create a view to display just one entry?

    Anyone care to help?

  • http://gravityfx.org/ emcgfx
    • TJ

      Nice, thanks for the link.

  • mehdi

    hi ,
    tanks for the good tutorials . i learn a lot but recently all video site are blocked in my country could you please put the videos on third party site like rapid share or something so we can use them . tanks

  • Wondering

    What happens, if insert in database fails? Or delete fails? How would you handle this?

  • dave

    Once again, fantastic tutorial that covers the bases necessary without going too far into the fluffy stuff! :)

  • Korenn

    You asked what the best practice is about the controller or the view picking up the segment to process. The answer is most definitely the controller. The controller is in charge of program flow, it decides where data comes from, how it’s processed and where it goes. The model should only process the data it’s given. When you make the model directly access input methods, you’re breaking that task division. A model shouldn’t care or know how data is supplied.

  • http://www.comoagrandarelpene.net como agrandar el pene

    It is a very well done tutorial, thanks

  • michael

    would liike to download this screencast.. i loaded every possible codeigniter tutorial, but some are not downloadable ;(

  • http://twitter.com/xrommelx xRommelx

    why this is not available in the PODSCAT

  • http://www.comoagrandarelpene.net como agrandar el pene

    This CRUD is not easy

  • Madalin

    Hello everybody,
    I have a little problem who really piss me off.
    Everything is working fine beside UPDATE.

    I have to hard code if I wanna get a satisfy result. I can mention that I was changing this function in every possible way and .. still not working.

    My code :

    function updateCommentsPerId($data) {

    $this->db->where(‘id’, $this->uri->segment(3)); // hard coding param2 => 18
    $this->db->update(‘comments’, $data);
    }

    The call :

    function updating() {

    $this->load->model(‘update_model’);

    $data = array(
    ‘author’ => $this->input->post(‘author’),
    ‘body’ => $this->input->post(‘body’),
    );

    $this->update_model->updateCommentsPerId($data);
    $this->index();
    }

    All I wanna do is making param2 from where clause dynamic.
    Seems like I have to get into black magic or asking a wizard for help.
    If you need the source code I can upload it somewhere.

    Thanks for help. I hope a wizard will hear my pain. :)

    • Michael

      Fantastic job.

      I went further than your tutorial did and added an edit link to each post, from where each post can then be updated. It all eventually went well with a bit of struggle here and there.

      My main problem was passing the ‘id’ from the edit page to the site_model class. I learned the big lesson that form_open() does not take variables (if you think otherwise kindly enlighten me), I tried the option form_open(“site/update/$this->uri->segment(3)”) n more ways than I thought I could imagine but to no avail.

      I eventually passed the id via a hidden form field and it sailed through.

      Your tots are welcome.

      any one interested in my edit/update code pm me.

  • Martino Wullems

    Catching up these series, very well introduction to codeigniter and MVC in general. I just have one question:

    When you create a new post (or any action actually) the URL gets appended with site/create to call the corresponding controller. Then the index controller is called again* to show the view of all the posts:

    function create(){

    $data = array(
    ‘title’ => $this->input->post(‘title’),
    ‘content’ => $this->input->post(‘content’)
    );

    $this->site_model->add_record($data);
    * $this->index(); //return to index
    }

    However, the URL still contains the site/create at the end when the action is completed, even after calling $this->index().

    I had to woraround for this, but I think theyre a little sloppy:
    1) Redirect to the index page directly.
    2) instead of calling the $this->create() to create a new post, check when the creation form is submitted:
    if($this->input->post(‘submit’)){//create post}

    I’m having a hard time trying to explain what I mean so I hope someone can help me out haha.
    Thanks in advance

  • Casper Larsen

    Hi, is there anyone who can post a link to a download in .MP4 format?

  • http://www.johntropeano.com Trope

    I spiced up the look , and came up with this for my first blog CRUD app in CI ….

    (screenshot)
    http://img685.imageshack.us/img685/6782/crud.jpg

    • miles

      trope,

      any chance you would offer this code – looks awsome

  • Chris Ellis

    Anyone found the solution to the problem of directly loading “index.php/site/create” directly into your browser. Apparently, for me at least, “index.php/site/delete/” with the id after it deletes as well. The question is how to prevent direct access.

    • komsaikoi

      you could make use of forms instead of the uri->segment(), and make a conditional statement

      if ($this->input->post(‘delete’))

      this tutorial is good and simple but it should be at the same time robust in handling uncontrolled data.

    • Flow

      I’m also wondering how to prevent direct access. Someone figured this out?

      @Jeff big up for this awesome series! I’m picking it up real quickly :)

  • Eoghan

    Thanks again Jeff, a wonderful course.

  • ci9

    @Jeffrey

    Thanks for this very nice tutorial i learned alot.

    I’ll pray for your good health.

    God Bless you Jeffrey.

  • BPfohl

    Love this tutorial… Newby question though

    I am having trouble with this working locally – I keep geeting this error:

    A Database Error Occurred
    Error Number: 1054
    Unknown column ‘$data’ in ‘field list’
    INSERT INTO `data` (`$data`) VALUES (”)

    Anyone else have that problem?

    • BPfohl

      Found it. I was passing a sting using ‘ ‘ – took the quotes and worked like a champ

  • Ronen

    What is the exact meaning of

    if($query = $this->site_model->get_records()

    Thanks.

  • Rick

    Ok – so is ANYONE ever going to answer the question re: getting this one on iTunes? Jeff?

  • http://stefan-cross.com Stefan

    Hum, its strange, i seem to have hit a wall half way through, just about kept up with the other 4 tuts in this series but im getting the following…

    Fatal error: Class ‘Site_model’ not found in /home/scross/development/ci/system/libraries/Loader.php on line 184

    Ill download the source and see if i can figure it out from that…

    Thanks for this series, its a real help!

  • Toni

    Jeff….this video is not avaliable anymore?

  • http://sold.ph Soldph

    You can directly download the video from

    http://a-mirror.video2.blip.tv/NETTUTS-CodeIgniterFromScratchDay5112.flv

    Cheers! :-)

  • http://about.me/mikkelz mikkelz

    Thanks for ALL the great tutorials – I really appreciate them!

  • http:www.parvaz-bd.webege.com jewel

    hi
    i cannot get any tutorial video on this page.
    it a add clip of Spice whisks. its a dings what i do it now.
    so, how i get the video tutorial ……………………………??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

  • Erfan

    Hi,
    Thanks for great lesson on CRUD.
    But i have a request if you can tell us how we will do all these orations dynamically, Because most the things you mentions in this lesson are hard coded.
    it would be highly appreciated if you can make it dynamically.

    once again thank you for your help.

  • ErikS

    Just started watching these a few days ago. Thru #5 at this point. Very helpful. Wish I had something like this years ago when I was starting out.

  • http://codersvenezuela.com uokesita

    For the people getting errors of “0 records” being created when loading “index.php/site/create”

    You can do something like if input(s) is(are) empty then go to the index page else create the record.

    You can also (and most secure) use the form_validation library that are reviewed in the tutorial 4 as this: https://gist.github.com/780711

  • Matthew

    Great tutorial. New to PHP and Codeigniter. I don’t know if anyone is still responding to comments, but anyone mind telling me how I would go about reading a single, individual post? I’m not sure if this was already covered, and apologies if it has, but how might I go about creating sort of “read more” link that directs the user to read just a single post?

    • Scott

      Day 2 covers that.

  • Nic

    Wow.
    That is the most complex way to do a CRUD I have ever seen.
    I gave up on your video when 15 minutes in you had failed to do the C in CRUD……..
    Why make it so complex?
    Doesnt code igniter have a CRUD plugin?

  • http://prabhasgupte.com Prabhas Gupte

    Nice screencast. Are you guys going to update the vids over the time as CI evolves and matures more?

  • http://www.colinmurphy.eu Colin

    Here is a way to update records Dynamically.

    View

    Update

    <option value="id; ?>">
    title; ?>

    Title

    Content

    No Records to Update :(

    Controller

    function update()
    {
    $data = array(
    'title' => $this->input->post('title'),
    'content' => $this->input->post('content')
    );

    $rowid = $this->input->post('rowid');

    $this->site_model->update_record($data, $rowid);

    $this->index();
    }

    Model

    function update_record($data, $rowid)
    {
    $this->db->where('id', $rowid);
    $this->db->update('crud', $data);
    }

  • http://www.colinmurphy.eu Colin

    Here is a way to update records Dynamically.

    View

    Update

    <option value="id; ?>">
    title; ?>

    Title

    Content

    No Records to Update :(

    Controller

    function update()
    {
    $data = array(
    'title' => $this->input->post('title'),
    'content' => $this->input->post('content')
    );

    $rowid = $this->input->post('rowid');

    $this->site_model->update_record($data, $rowid);

    $this->index();
    }

  • Madoc

    Hi there,

    Great Tutorials so far ! Can’t wait to get stuck on #6.

    Quick question:
    - Are you guys really using the url method to delete and update records on your CI projects ?
    - If so how do you prevent users from deleting random records by using the url and changing the id for instance ?

  • jeric realubit

    thanks! ;)

  • Victor

    Can someone make a tutorial about updating entries please (video)

  • Michael Insalaco

    I have CI 2.0.2 and autoloading the Site model breaks the app. it seems like any framework that is updated to a new version makes previous tutorials obsolete.