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
  • http://digitalnacarolija.net Tomica

    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.

  • Steve

    @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)

  • http://digitalnacarolija.net Tomica

    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);

  • http://digitalnacarolija.net Tomica

    Sorry for re-posting, I have made another typo there. What I meant was:

    $this->load>view(‘includes/template’, $data1, $data2);

  • http://digitalnacarolija.net Tomica

    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.

  • http://www.willdonohoe.com Will

    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

    • Ian

      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.

  • http://adardesign.com adardesign

    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

  • Raniem

    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 ;)

  • http://dsad Jeezus

    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.

  • Stephen

    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’);
    }

    }

  • Jubic

    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?

    • Jubic

      A clearer view of the codes: http://codr.cc/e915d0

    • Ian

      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.

  • http://creativity-works.net Dave March

    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.

  • http://creativity-works.net Dave March

    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:

  • KerryCoda

    Do a tutourial on php shorthand….cuz i don’t competely understand them.

  • Robert

    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?

  • Nuruzzaman Sheikh

    Hey Jeff,
    Actually this video link is dead, can you help us?

  • Alvaro Uribe

    Im in love !

  • QuestionBoy

    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!!!!!

  • Matt

    Thank you so much for these wonderful tutorials! Great job!

  • Met

    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

  • kyouya

    hi Mr. way,

    we have encountered an error in the code u have provided at codeigniter day 5.

    in the delete method on the site_model.

    the error is:

    A php error was encountered

    severity: notice

    message: undefined property : site_model::$url

    filename: model/site_model.php

    we have followed the code that u do on the screencast, but still we cnt find the error.

    it’s been difficult 2 debug.

    can you help us please. tnx

    • Rodolfo

      When you write $this->url->… you need to use an ” i ” like so: $this->uri-> …

  • kyouya

    hi Mr. way,

    we have encountered an error in the code u have provided at codeigniter day 5.

    in the delete method on the site_model.

    the error is:

    A php error was encountered

    severity: notice

    message: undefined property : site_model::$url

    filename: model/site_model.php

    we have followed the code that u do on the screencast, but still we cnt find the error.

    it’s been difficult 2 debug.

    can you help us please. tnx

    • waseemmachloy

      May be it help u
      i think u missing this
      $this->load->helper(‘url’);
      OR
      go to config folder autoload.php
      on line 67 change
      $autoload['helper'] = array();
      to
      $autoload['helper'] = array(‘url’);

  • http://www.dragoviandesign.be Peter Vermeulen

    Superb tutorial but one thing bugs me, when you add/create/update/delete a record, you call the index() function and it does execute it. However, the url stays the same.

    What i mean is, consider you press the anchor tag of an item with id 5.

    The url will stay /site/delete/5 whilst your in fact on the index.

    is there any solution to this ?

    • Dong

      im also trying to figure out this index function, wondering if i did something wrong, any solution to this?
      btw, this one is working for me, redirect(‘/site/’, ‘refresh’); any thoughts?

  • Marfin

    database error, please help me

  • Thilak

    These tutorials are just great. Simple and interesting.

    Thanks Jeff.

  • Raphael Godoi

    Parabéns pelo artigo muito bom!!!

  • Harry Mavidis

    Very nice tutorials!

  • Jahanzeb

    Just the tutes I needed. Thanks.

    Just in case anyone sees this post, I have to include the site model with every function, why?

    (Using CI 2.1.2)

    • http://aftonbladet.se Smartin

      I have the very same problem and even when included I get the 500 internal error anyway. Can’t even get the create function working! Gaw!

    • Miglos

      You mean the one in the autoload file? I’m using CI 2.1.2 too and everything works just fine.
      $autoload['model'] = array(‘site_model’);

  • Muhammad

    hi, i have face problem when I post the page,plz help me

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Site::$Site_model

    Filename: controllers/site.php

    Line Number: 16

  • http://www.kfgnyc.com deepak

    hey
    I use codeIgniter 5 day crud lesson show error This webpage is not available ssl error when I insert the record throw the form

  • saideep

    Thanks for sharing the valuable tutorials with us..We are really enjoying the codeigniter and u r tutorials

  • Matthew

    This series is great!

    One problem for me though… The “Update” function is the one I have the most trouble learning. And that’s the one this video kind of races through.

    Is there any way to expand this video, or do another one that explains the “update” function better?

    Thanks!

    • suricatita

      I’m having trouble with this one too :/

  • CI guy

    How would you dynamically pass the table name to the model? I ask because I am thinking I could just use the one site_model to handle any of my sites CRUD needs although my site utilizes more then once table, example I have a users table as well as a articles table so how could I make my page that does insert or updates for my articles pass the articles table name to the site model file vs the users updates file which would need to pass the table name users to the site model file

    thanks

  • mudahdingat

    is there something wrong with blip.tv ? the video isn’t come up

  • someone

    video isn’t coming up!!!

  • Deepak

    great tutorial , how to create gift certificate web appiliction in codeigniter

  • nishant

    i have made login form and in form action i have provided class name of controller(site)/method name(insert_into_db)…so when i press submit button insert operation is done but page is redirected so any sollution so that i can stay on same page

  • yamasnax

    When I run ‘$this->db->insert(‘data’, $data)’, I see extra 0 0 row data in MySQL database. Anyone have any ideas why this extra rows insert?

    • yamasnax

      Figured it out. I disabled my chrome extension “HTML Validator” then stop running the query twice.

  • mudahdingat

    ecountering database error
    ————————————————————————————————-
    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 `crudtable` (`) VALUES (”)

    Filename: D:xampphtdocsCIBsystemdatabaseDB_driver.php

    Line Number: 330

    —————————————————————————————————-
    insert function at controller file

    function tambahdata()
    {
    $data = array(
    ‘title’=>$this->input->post(‘title’),
    ‘content’=>$this->input->post(‘content’),
    );
    $this->modelcrud->add_value($data);
    $this->index();

    }

    ——————————————————————————————–
    insert function at model file

    function add_value(){
    $create=$data;
    $this->db->set($create);
    $this->db->insert(‘crudtable’);
    return;
    ——————————————————————————————–
    is there any solutions for my problem ?

  • Sanjay Maurya

    Hi Jefferey,

    Thanks for such a good tutorial on this topic. It was simple to understand. Everything worked fine at my end.

    One question ‘?’:
    When I hit submit button, the URL of the page changes to http://localhost/CI/index.php/site/create. The URL remains the same when we are redirected back to view page index(). The problem with this is that when if I hit the same URL again, there is error on page as fields are empty. This is just because “create” stays in the URL. Is there way to just load http://localhost/CI/index.php/site only after CRUD operation?
    Thanks,

    • suricatita

      I added this line in the create function of the controller

      redirect(base_url(‘site’));

      • Sanjay Maurya

        Thanks Suricatita.

      • John K

        That didn’t work for me, but this did:

        redirect(site_url(‘site’));

  • Notlfip

    In the create part, the $this->index(); isn’t working i think.. when i add something i stay on the site/create page.. and when i F5 empty rows are being added to the database

    Any ideas?

  • http://www.facebook.com/Sagar.S.Shinde Sagar Subhash Shinde

    Again Awesome tutorials.

    Just that I wanted to get the full flow of the concept. Like updating from values from user.

    I would have love if you have a video of a whole project as such. like starting from scratch. M being hooked to this tutorials.

  • ghost

    for people that have trouble with $this->db->where('id', $this->url->segment(3));

    chenge the URL to URI

    it has to be an i instead of a l

    ps: great tuts :)

  • Kd

    Nice but there is another nice tut for crud

    http://www.grocerycrud.com/examples/full_example

  • Suyog

    After watching 5 tutorials, I have just one thing to say…..”Jeffrey Way is THE BEST”