CodeIgniter From Scratch: Day 2
videos

CodeIgniter From Scratch: Day 2

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

Continuing on from day 1, today, I’ll teach you five different ways to write select statements for your database. If you haven’t watched the first entry in this video series, don’t worry; each video can function on its own as a single tutorial. Having said that, I highly recommend that you watch each screencast.

Catch Up

Day 2


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

    “SELECT title, author, contents FROM data WHERE id = ? AND author = ?”;

    id = primary key. It will NOT find more rows than 1.

    • Pat

      He didn’t specify or imply that the method would return more than one row, he just wrote down a WHERE close using a type off of his head.

      Not to mention that this method also make’s sense if you decided to name it getContsAndTitleById($id) to retrieve a specific row by passing the id as the parameter.

      If you were looking for a real-world example, think of a book table with an ISBN column type, it would make sense to have a function that would retrieve the book by it’s unique identifier.

      Regards,

      Pat

  • binary

    simply return $q->result(); makes function getAll() more smaller instead of adding it to another array called $data.

    • http://www.danielvigueras.com Daniel Vigueras

      He copies the resulting rows to a $data array in order to be able to do a $q->free_result().

      Freeing the result is a good practice if you are going to make more sql queries and you want to keep the memory usage low.

      • Alfred

        Been a while since I’ve used PHP so I can’t remember whether it’s by reference or by value etc. but what about:

        $data = $q->result();
        $q->free_result();

        return $data;

        ??

    • http://www.pixellarize.com elimsekaf

      First of great tutorial. :)

      if the query returns more than one row of data it is necessary to loop $data = $q->result() to return all the rows, since result() returns only one row of the queried results.

      how ever if the query was to return only one row there is no need for the loop..

      i think the author of the tutorial copied the loop to make the tutorial scripting easy and intentions where to show some to the ways to query a database in CI.

      Thanks for the great tutorial again.. :)

  • Johan

    Hi

    I have a problem with UTF-8 charset. Iam swedish so i use letters as “å, ä, ö”.
    When i connect to my “db” all l”å, ä, ö” cant show. I have tried to search but dont really know what to do. It has been working before i started to use Codeigniter. I´ll tell you i´m a beginner. ;)

    I have tried the “meta tag” with UTF-8 and then all content from the “db” shows correctly but not the regular HTML?

    Any suggestion?

    • Andres

      You must set the collation to utf8_general_ci. Check the connection to the database, then the fields and tables collation to utf8_general_ci, and don’t forget your file .php must be in utf8.

      If you set the all the codification to UTF8 it won’t be a problem.

  • http://paulvoth.net Paul

    Thanks for these great tutorials. I’m just starting out with CodeIgniter so this is a great help.
    However, I’m having some trouble with the code in this tutorial.
    At the end of the tutorial when everything is done, I’m getting PHP errors when visiting the endresult through my browser:

    Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\htdocs\ci_day2\system\codeigniter\Common.php on line 130

    Deprecated: Assigning the return value of new by reference is deprecated in C:\xampp\htdocs\ci_day2\system\codeigniter\Common.php on line 136
    A PHP Error was encountered

    Severity: 8192

    Message: Function set_magic_quotes_runtime() is deprecated

    Filename: codeigniter/CodeIgniter.php

    Line Number: 60
    A PHP Error was encountered

    Severity: 8192

    Message: Assigning the return value of new by reference is deprecated

    Filename: libraries/Loader.php

    Line Number: 255
    A PHP Error was encountered

    Severity: 8192

    Message: Assigning the return value of new by reference is deprecated

    Filename: database/DB.php

    Line Number: 133

    ————–
    Any idea what the problem is? Is CodeIgniter not compatible with my PHP version (5.3.0)?

    • http://paulvoth.net Paul

      I checked out the latest version of CodeIgniter via SVN and that solved the problem. It was a compatibility issue with PHP 5.3.0.

      Again, thanks for these awesome tutorials. :)

  • monika

    wow…!!this tutorials is so much worth for CodeIgniter learnes..!!CodeIgniter rocks.

  • fish mouth

    Wicked series Jeffrey, thanks so much

  • http://blog.sunghwanyoo.com SH

    Thank you, it was really helpful.

  • adelle

    Such a Great Thing .. Thanks Jeff

  • http://www.kitfoxink.com/ Kit

    Wow, binding is way better than typing mysql_real_escape_string() over and over.

  • http://gravityfx.org/ emcgfx

    Direct Link to the video:

    Day 2: Database Selecting Methods
    http://a-mirror.video2.blip.tv/NETTUTS-CIDay2743.flv

  • Dev

    Hey… Jeff. great work…..

    i am not able to watch online video so can you give me direct link to download videos for learnning

    Thanx….

    Dev.

    • Dev

      can you give me all links please….

      thanks…

  • Dymakel

    I’m new to php & MVC. Love the videos, you make it easy to understand. Thanks!

  • http://www.knickmedia.com Nick

    Great tutorial. I’m moving over to Code Igniter from Zend Framework. Much simpler to use technology. One tip though that might be useful to others… rather than constantly repeating your iteration, why not use a helper function like this:

    function _constructData($q) {

    if ($q->num_rows() > 0) {

    foreach ($q->result() as $row) {

    $data[] = $row;

    }

    return $data;

    }

    }

    And then from any getter, you can just do this…

    function getAll() {

    $q = $this->db->get(‘posts’);
    return $this->_constructData($q);

    }

    That way you save a lot of typing and you don’t repeat code all over the place which can increase the chance of error.

    • ennism

      Great suggestion Nick – I can see the some of the Zend Framework thinking coming out. I just turned to CodeIgniter as I am currently struggling to understand Zend Framework. Maybe you could start a tutorial on Zend Framework (particularly how to configure when using modules), if you haven’t already done so.

      Thanks again for the suggestion.

  • Linker3000

    Thanks for the great tutorial – I am just beginning with CI and this is the kind of stuff I need. I have not done much object-oriented programming so the concept is still a bit weird!

    I have taken the example code and modified it to run a query on one of my databases and this works fine, but I am struggling to make it handle queries that return no results; I have slightly modified part of the model like this:

    if ($query->num_rows() > 0) {
    foreach($query->result() as $row) {
    $data[] = $row;
    }

    }
    return $data;

    and was hoping I could just add an else condition before the ‘return’ that set one element of $data to something like ‘No data returned’, but I clearly haven’t go the concept right eg (excuse the formatting):

    else { $data = array(“retval” => “No data returned”) ; }

    But that gives me “Trying to get property of non-object” in the view.

    Am I heading along the right lines or is there a better approach to handling no results within the example code?

    Thanks

    • http://praveeng.com arjun

      return $data must be inside the if condition

  • Ondiamond

    How can happen ? on line 42 of data_model file you try wrong query and you get error message on foreach ! but you check query with num_rows ! how you get error ?!
    this is wrong !!!

  • Rahul

    Great tutorial. I may be a year late to the party, but this is very well done, Jeffrey.

    I had a question about what limits should be set on a model class. Say I have a database table named “questions” which houses lots of multiple choice questions, the right and wrong answers, and various statistics (how many times attempted, how many times answered correctly, etc).

    Should a model be limited only to getting the data into and out of the database table? Or can it also provide other functionality like randomize the order of the answers, calculate statistics on the question.

    I may pull a marathon nettuts session! Thanks again!

    - Rahul

  • http://www.grabanddev.com/HMS/ ruinze

    very clear for starters..thank you for this

  • http://www.topteacher.co.kr pooo6

    wow !! Thank you very much

  • Brian

    I just wanted to extend my thanks for you taking the time to put these tutorials together, they really help me as I dive into deeper waters.

  • http://imtiaz.mallick.ws Imtiaz

    Beautiful tutorial, I liked the way you demonstrate the teaching with example, it really helped me to understand the CI better. MVC was something I struggled to understand but you have put together the tutorial very well.. I am now more comfortable with MVC framework.

  • Elliott

    Anyone notice Jeffrey sounds a bit like Adam Scott?

  • Juris M

    thank You for Your good work ;-)

  • http://www.stewanpacheco.com Stewan

    great :D

  • prasan

    if the table is empty then it is giving a warning:

    invalid argument supplied for foreach()

  • sachin

    good job boss

  • http://ashpointlane.com angst

    I am looking for a tutorial for defining the database name to connect to by reading the first URI segment. Every tutorial for db connections points to setting static parameters in the database.php config file for each database you have. I have several hundred small databases to connect to with my api and cannot set all all those statically in a config file. I have created a user/pass combo that is only allowed to SELECT on each of these databases so all i have to set to connect to any of these databases is the name iteself. If I want to set $this->uri->segment(1) in the database.php what would I have to do? Is that even the best way to handle this? I’m looking for suggestions…

  • Dan

    U r so awsome…thanks…

  • Rahul

    Dude you are the Best… Thank you for your tutorial.. It really helped me. :)

  • Wattswing

    Thanks a lot ! :)
    Great tutoriel/sugestions
    It helps a lot, wonderful !

  • http://www.wpvine.com Vishu

    Great tut Jeff! I finally gave CodeIgniter a go after watching this and the day 1 vid, now I’m gonna finish the series and build my second php application, built my first app as a college project and I wonder why I didn’t use CodeIgniter before! saves so much work!!

    Thanks a lot once again, you’re my Guru :D

  • Angelo

    Thank you :) this is the only very GOOD tutorial online

  • jogc

    I’m new to nettuts, so sorry if this is a silly question.

    I saw the part 1 of the series without problems but when I try to watch any other part, I always get an error, as if the video did not exists.

    Are the videos on this series free of charge?

    Thanks for your help.

  • Ana

    I’m on http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-2/ and its playing Ruby for Newbies! …
    By the way, is there any way to download the codeigniter series?

  • http://dagrevis.lv/ daGrevis

    He, he. Too many ways to do one simple task! =D I prefer to write my queries using “I write queries” method. =]

  • http://www.adbhuth.in aditya menon

    codeigniter really cleans up my MESSY implementation of data retrieval.. previously, it was like i’m making sure i leave little nightmares for myself everytime i write a protracted db select query – and god help me if i made a mistake and/or want to make changes.

    now, it is really a “before, after” miracle! thanks :) keep going with this site. it is just awesome :)

  • http://www.eycone.com goosy

    God bless u !!!! Thanks a lot for those screencasts

  • Kevin

    I keep getting an error message and can’t seem to resolve it… I looked at the CI user guide and can’t seem to find anything that I’m doing wrong. I even re-typed the code and can’t seem to see any typos.

    ——————————-
    Error is:
    A PHP Error was encountered

    Severity: Warning

    Message: Invalid argument supplied for each()

    Filename: views/home.php

    Line Number: 16
    ——————————-
    The code on Line Number 15, 16, 17, 18, and 19 of home.php is:

    <?php
    foreach ($rows as $r) {
    echo '’ . $r->title . ”;
    }
    ?>

    ——————————-
    I read at php.syntaxerrors.info that sometimes “invalid argument supplied foreach() can happen if you try to do a foreach on a variable that isn’t an array”… is this not an array? can I have a typo somewhere else that may cause this? Thank in advance for any help provided, really hoping to get over this hump… excited to get a grip on CI.

    • nobody

      Your query is probably not returning any results therefore there is no array, hence the error.

  • Kevin

    I keep getting “Warning: #1366 Incorrect integer value:” errors when trying to insert into the fields of the database table…. I can’t seem to figure out what is causing this. Any help you can provide would be greatly appreciated.

  • champi

    A big thanks to you.

    I’m french and I don’t understand everything in your videos but the main idea conveyed.
    So thanks again !!

    Scuse me for my bad grammar :>

  • Bogdan

    Hey. I would like to put the ‘view-objects’ on screen only if its from a list of users(Database users) which they have passwords. How should I need to set the $db['default']['username'] = ‘root’; $db['default']['password'] = ‘root’; from config/database.php file ? Thanks alot and also, a great tutorial !

  • http://www.learneveryday.net arifur rahman
  • bill

    There doesnot appear to be any demo SQL file to download.

  • Nasir

    Hey Jeffrey,

    Thanks for these tutorials, these are really helping me learn PHP in no time.

  • Anthony

    Ok. I have watched all the CI from Scratch videos from beginning to end. Nicely Done!!

    Now I am trying to actually put to use what I watched. Day 1 went without a hitch. I have moved my system folder (CI version 2 – most current download avail) to outside of my htdocs folder. Made the applicable changes. Everything works. Until I get to day 2.

    On day 2 at time mark 13:00 minutes, I am getting a http404 error and not a data() listing of a graphic. It threw me for a loop, until I noticed that I was getting the following url in my browser when I clicked submit.

    http://localhost/index.php/index.php/upload/doUpload

    notice the 2 index.php back-to-back??

    Why am I getting this??? Has anyone run onto this???

    Here is the controller file:

    class Upload extends CI_Controller {

    function index() {
    $this->load->view(‘upload_form’);
    }

    function doUpload() {
    $config['upload_path'] = ‘pics_Movys/dogPics/’;
    $config['allowed_types'] = ‘gif|jpg|jpeg|png’;
    $config['max_size'] = ’1000′;
    $config['max_width'] = ’1920′;
    $config['max_height'] = ’1280′;

    $this->load->library(‘upload’, $config);

    if(!$this->upload->do_upload()) echo $this->upload->display_errors();
    else {
    $fInfo = $this->upload->data();
    echo ”;
    print_r($fInfo);
    echo ”;
    }
    }
    }

    And here is the view file:

    Upload an Image

    I have tried putting my upload directory both inside of my application folder and outside my application folder. But I get the same response.

    If you should show me where I am a ‘bone-head’, I would greatly appreciate it.

    Tony

  • carmen

    Hi, Can you tell us how to use the xml database instead sql in codeigniter…. Thanks

  • Gav

    Hi guys – running CodeIgniter 2.0.2 and get the following errors..

    Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set()
    Any ideas?

  • Klauss

    I can’t watch. Keep stuck at loading after the advertising…

  • basitjee

    Cool, fantastic

  • Alex

    I enjoy thanks jeffrey way (hero)

  • Phani

    Hello,

    I am beginner to CodeIgniter. These videos are really very help full. Unfortunately i cannot download the day 2 source code zip file. If possible please send me the source code of day 2.

    Thanks
    Phani