williamsdb
williamsdb

Reputation: 1064

How to access the database from a Codeigniter CLI

I have a Codeigniter application that works well through the browser but I am struggling to get anything working properly on the command line. The following snippet is what I have in my controller:

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

class Followers extends CI_Controller {

  public function process()
  {
    echo ENVIRONMENT.PHP_EOL;

    $this->db->select('n.`id`, n.`name`');
    $this->db->from('`table` n');
    $this->db->where('n.`active` = 1');
    $query = $this->db->get();
    $results = $query->result_array();

  }

}

I run as follows:

php index.php cli followers process

And get the following:

development

A PHP Error was encountered

Severity:    Notice
Message:     Undefined property: Followers::$db
Filename:    /Users/neilthompson/Dropbox/Development/MAMP/htdocs/app/application/controllers/cli/Followers.php
Line Number: 14

Backtrace:
    File: /Users/neilthompson/Dropbox/Development/MAMP/htdocs/app/application/controllers/cli/Followers.php
    Line: 14
    Function: _error_handler

    File: /Users/neilthompson/Dropbox/Development/MAMP/htdocs/app/index.php
    Line: 343
    Function: require_once



An uncaught Exception was encountered

Type:        Error
Message:     Call to a member function select() on null
Filename:    /Users/neilthompson/Dropbox/Development/MAMP/htdocs/app/application/controllers/cli/Followers.php
Line Number: 14

Backtrace:
    File: /Users/neilthompson/Dropbox/Development/MAMP/htdocs/app/index.php
    Line: 343
    Function: require_once

I understand what the error is saying but not how to fix it!

I have the following in the autoload file:

$autoload['libraries'] = array('database', 'smartie' => 'smarty', 'session');

What do I have to do to be able to access the database?

Upvotes: 0

Views: 682

Answers (1)

williamsdb
williamsdb

Reputation: 1064

The issue turned out to be that running on the command line it didn't like using the hostname "localhost" to connect to the database. Changing this to 127.0.0.1 fixed it.

Upvotes: 2

Related Questions