4

I'm new to CodeIgniter and trying to developing a fairly simple application with it -- just a form to process the registration for employees wanting a recreation center pass. I'm trying to separate things to make them cleaner.

Here is the code:

application/controllers/reccenter.php

class RecCenter extends CI_Controller {

    public function register() {
        $data['title'] = "Utah Valley Rec Center Registration";

        $this->output->enable_profiler(TRUE); // Put all the debug statements at the bottom of the page
        $this->load->helper('html');

        $this->load->library('form_validation');
        $this->form_validation->set_rules('userRecCenter', 'recreation center selection', 'required');

        $userRecCenter = $this->input->post('userRecCenter');
        $registerSelf = $this->input->post('registerSelf');
        $dependents = $this->input->post('dependents');

        if($this->input->post('registerSelf') && !$registerSelf) { // Employee not registering themselves
            $this->form_validation->set_rules('dependents', 'self selection or dependents', 'required');
        } else if($this->input->post('dependents') && count($dependents) == 1 && $dependents[0] == "") { // Employee only registering themselves
            $this->form_validation->set_rules('registerSelf', 'self selection or dependents', 'required');
        }

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('pages/reccenter/register', $data);
            $this->load->view('templates/footer', $data);
        } else {
            $this->load->library('Reccenterdao');
            $numRows = $this->reccenterdao->getRecCenterInfo();
            var_dump($numRows);

            // Check if already registered 
                // Redirect to different view to change their registration

            // Do the registration
                //redirect('reccenter/confirm');
        }
    }

    public function confirm() {
        $data['title'] = "Utah Valley Rec Center Registration Confirmation";

        $this->load->view('templates/header', $data);
        $this->load->view('pages/reccenter/confirm', $data);
        $this->load->view('templates/footer', $data);
    }
}

application/libraries/Reccenterdao.php

if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Reccenterdao {

    private $CI;

    public function __construct() { 
        $this->CI =& get_instance();
    }

    private function connect() {
        $this->CI->load->database();
    }

    private function disconnect() {
        $this->CI->db->close();
    }

    public function getRecCenterInfo() {
        $this->connect();

        var_dump("Made it here");
        $result = $CI->db->query("SELECT * FROM ucfitness");
        var_dump($result->result());

        $this->disconnect();
        return $result->num_rows();
    }


}

Here are a couple of additional configuration items, so you know what all I've done to customize it a bit.

application/config/autoload.php

$autoload['helper'] = array('form', 'url');

webroot/index.php (For environment definitions)

if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == "my prod server") {
    define('ENVIRONMENT', 'prod');  
} else if(isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == "my stage server") {
    define('ENVIRONMENT', 'stage'); 
} else {
    define('ENVIRONMENT', 'test');  
}

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'test':
            error_reporting(E_ALL);
        break;

        case 'stage':
        case 'prod':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

I've also copied application/config/database.php into three folders, application/config/test/database.php, application/config/stage/database.php, and application/config/prod/database.php, to configure their individual connection parameters. Each environment has a different database server and credentials.

The problem is that when I submit the form and it makes it in to that else statement after the form validation $this->form_validation->run() I'm getting only a blank screen. None of my desperate var_dumps, nothing. So, after all of my attempts and different methods of getting this to work, a few questions have come up.

  1. What isn't working in the library? After going through all the tutorials/questions that I can find, it looks like I'm doing it right.
  2. How do I make it so that I can actually debug the code? I get no errors in the browser and no errors on the Apache error log. What else can I do?
  3. What would the best practice be for separating the DAO from the Controller? From what I could tell, making this a library like I'm trying would be the best idea. It is probably only going to be used by this one controller, which will handle both registration and modification of the registration. I will be writing a couple of other applications that will all sit within this CI instance, but they're going to be fairly separate and will not need to use the same DAO.
  4. Can I use CamelCase for the library file name as long as it starts with a capital letter? Reccenterdao.php is a lot less friendly than RecCenterDAO.php.

============================================================

EDIT: I changed the whole thing to a model, but I'm getting the same functionality - blank screen with no errors. It seems to load the model, because it dies when I try to actually use it with the line $numRows = $this->dao->getRecCenterInfo();

I know the whole thing is pointless right now because I haven't put functionality to use the database or parse the user input. That's the whole point. I was trying to get it to work before I went through the effort of putting in all my business logic.

application/models/rec_center_dao.php

class Rec_center_dao extends CI_Model {

    public function __construct() { 
        parent::__construct();
    }

    private function connect() {
        $this->load->database();
    }

    private function disconnect() {
        $this->db->close();
    }

    public function getRecCenterInfo() {
        $this->connect();

        var_dump("Made it here");
        $result = $this->db->query("SELECT * FROM ucfitness");
        var_dump($result->result());

        $this->disconnect();
        return $result->num_rows();
    }
}

Relevant section of application/controllers/reccenter.php

    if ($this->form_validation->run() == FALSE) {
        $this->load->view('templates/header', $data);
        $this->load->view('pages/reccenter/register', $data);
        $this->load->view('templates/footer', $data);
    } else {
        $this->load->model('Rec_center_dao', 'dao');
        $numRows = $this->dao->getRecCenterInfo(); // This is where it dies
        var_dump($numRows);

        // Check if already registered 
            // Redirect to different view to change their registration

        // Do the registration
            //redirect('reccenter/confirm');
    }

============================================================

EDIT2: Thanks to the comments, I've figured out that it's a problem connecting to the database. It errors out when I call $this->load->database();. I've confirmed that with the credentials I have I can manage the database with phpMyAdmin (I don't have shell access to test there).

application/config/test/database.php

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'my.hostname.com';
$db['default']['username'] = 'db_username';
$db['default']['password'] = 'db_password';
$db['default']['database'] = 'db'
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = TRUE;

With the above configurations in webroot/index.php and application/config/test/database.php it should pick up the settings for the different environments and take care of it accordingly, correct? But if I put a var_dump in either application/config/database.php or application/config/test/database.php it doesn't show up at all. I confirmed that the environment is being set correctly (at least while I'm working on test).

8
  • You need to enable PHP error reporting otherwise you'll get a blank screen, CI does it by default for a development environment, check the "Error reporting" section inside webroot/index.php and accommodate for your custom environments. Also why not use a model instead of a library? finally, you can have CI manage your DB connection automatically, of course it's your choice if you want to do it manually Commented Nov 27, 2013 at 18:34
  • I thought that I had done that. I added the code up above so you can see. Looks like my logic for the environment definitions isn't working correctly. I considered having CI manage the connection, so maybe I'll look into that again... Now that you say it, a model seems like it would make more sense, especially since I'm not reusing the library. Maybe I'll take a look into that Commented Nov 27, 2013 at 18:41
  • I changed it all to a model but I'm still getting the same errors. I also tried to change the error logging to do the same E_ALL for all environments, but I still ended up with no errors anywhere that I could find. Commented Nov 27, 2013 at 19:01
  • That's weird, can you check the result of var_dump($this->dao); before calling the getRecCenterInfo method? I guess the next debug step would be to start placing die()s at each line to see where exactly it is failing Commented Nov 27, 2013 at 19:19
  • The result of var_dump($this->dao); is object(Rec_center_dao)#16 (0) { } Commented Nov 27, 2013 at 19:44

2 Answers 2

1

Surely, your class has these errors (the rest of the code looks fine):

private function connect() {
    $CI->load->database();
}

Should be:

private function connect() {
    $this->CI->load->database();
}

Since you've assigned $this->CI in the constructor, and you want to use that class property, not just a newly created $CI variable. Same goes for the disconnect() method, which should be:

private function disconnect() {
    $this->CI->db->close();
}

Then, here:

public function getRecCenterInfo() {
    connect();

    var_dump("Made it here");
    $result = $CI->db->query("SELECT * FROM ucfitness");
    var_dump($result->result());

    disconnect();
    return $result->num_rows();
}

You should have instead (errors highlighted in the comments):

public function getRecCenterInfo() {
    $this->connect(); // it's a method in the class, not a regular function
    $result = $this->CI->db->query("SELECT * FROM ucfitness"); // The property is $this->CI
    $this->disconnect(); // same as $this->connect();
    return $result->num_rows();
}

Aside from these errors, your class so far it's pretty useless, you would achieve the same using the DB class, maybe autoloaded, in a regular model.

Sign up to request clarification or add additional context in comments.

3 Comments

I changed my code to what you suggested, but that still didn't solve it. As a side note, I thought that I couldn't use $this in a library, and had to use the $CI because of the way that CI handles libraries. But it would make sense that it just does that for CI stuff and then I can still use $this for in-class things.
You can't use $this as the reference to the main CI object you see in model/controllers and views, but $this here needs to be used since you want to refer to properties / methods of that class.
Got it. I changed everything to be a model instead of a library. Please take a look.
0

Turns out the problem was my PHP installation. I'm running Windows 7 and used the MSI installer to install PHP 5.2.14. I used the php-5.2.14-Win32-VC6-x86.zip to redo the installation. Unzipped it, put it in place, reconfigured the php.ini, and it worked.

Don't use the MSI installers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.