CodeIgniter Sqlite not working - php

Whenever I query my database (sqlite) like this in my model (im using codeigniter, full code below):
$this->db->select('post');
$query = $this->db->get('posts');
return $query->result_array();
I get the following error:
Fatal error: Call to a member function rowCount() on a non-object in /codeigniter/system/database/drivers/pdo/pdo_result.php on line 42
When changing the query to something nonexistent I get a "proper" error, something like:
A Database Error Occurred
Error Number: HY000
no such column: posst
SELECT posst FROM posts
Filename: /codeigniter/models/post.php
Line Number: 8
Which leads me to believe the database is actually working, but there is something I am missing.
I have tried recreating the database. It literally has 1 table with 1 column, but I just cannot get any data out. I also tried creating it with different "admin" programs but to no avail. I made sure it is an Sqlite 3 db, which is supported by the webserver according to phpinfo.
Does anybody have a clue where I am making a mistake?
-------- full code:
my post model in models/post.php
<?php
class Post extends CI_Model{
function get_posts(){
$this->db->select('posst');
$query = $this->db->get('posts');
return $query->result_array();
}
}
My controller in controller/posts.php :
<?php
class Posts extends CI_Controller{
function index(){
$this->load->model('post');
$data['posts']=$this->post->get_posts();
echo"<pre>";
print_r($data['posts']);
echo"</pre>";
}
}
My database config in database.php :
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'sqlite:/home/******/******/www/wtp3/codeigniter/db/wtp35.sqlite';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'pdo';
$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'] = FALSE;

Credits for this fix are with S. Stüvel, J. Bransen and S. Timmer. This is a fix for a specific server, so YMMV. It did the trick for me though.
In pdo_driver.php, starting line 81 change:
empty($this->database) OR $this->hostname .= ';dbname='.$this->database;
$this->trans_enabled = FALSE;
$this->_random_keyword = ' RND('.time().')'; // database specific random keyword
}
to
if(strpos($this->database, 'sqlite') !== FALSE) {
$this->hostname = $this->database;
$this->_random_keyword = ' RANDOM()';
}
else {
$this->hostname .= ";dbname=".$this->database;
$this->_random_keyword = ' RND('.time().')'; // database specific random keyword
}
$this->trans_enabled = FALSE;
}
On line 189 change the entire function _execute($sql) to
function _execute($sql)
{
$sql = $this->_prep_query($sql);
$result_id = $this->conn_id->query($sql);
if (is_object($result_id))
{
$this->affect_rows = $result_id->rowCount();
}
else
{
$this->affect_rows = 0;
}
return $result_id;
}
Then in pdo_result.php change":
On line 29 change
public $num_rows;
to
var $pdo_results = '';
var $pdo_index = 0;
on line 36 replace entire function
public function num_rows()
{
if (is_int($this->num_rows))
{
return $this->num_rows;
}
elseif (($this->num_rows = $this->result_id->rowCount()) > 0)
{
return $this->num_rows;
}
$this->num_rows = count($this->result_id->fetchAll());
$this->result_id->execute();
return $this->num_rows;
}
with:
function num_rows()
{
if ( ! $this->pdo_results ) {
$this->pdo_results = $this->result_id->fetchAll(PDO::FETCH_ASSOC);
}
return sizeof($this->pdo_results);
Then on line 60 change
function num_fields()
{
return $this->result_id->columnCount();
}
to:
function num_fields()
{
if ( is_array($this->pdo_results) ) {
return sizeof($this->pdo_results[$this->pdo_index]);
} else {
return $this->result_id->columnCount();
}
}
Then on line 94 change:
function field_data()
{
$data = array();
try
{
for($i = 0; $i < $this->num_fields(); $i++)
{
$data[] = $this->result_id->getColumnMeta($i);
}
return $data;
}
catch (Exception $e)
{
if ($this->db->db_debug)
{
return $this->db->display_error('db_unsuported_feature');
}
return FALSE;
}
}
to:
function field_data()
{
if ($this->db->db_debug)
{
return $this->db->display_error('db_unsuported_feature');
}
return FALSE;
}
then line 146 change:
return FALSE;
to
$this->pdo_index = $n;
then on line 159 change
function _fetch_assoc()
{
return $this->result_id->fetch(PDO::FETCH_ASSOC);
}
to
function _fetch_assoc()
{
if ( is_array($this->pdo_results) ) {
$i = $this->pdo_index;
$this->pdo_index++;
if ( isset($this->pdo_results[$i]))
return $this->pdo_results[$i];
return null;
}
return $this->result_id->fetch(PDO::FETCH_ASSOC);
}
And finally on line 174 change:
function _fetch_object()
{
return $this->result_id->fetchObject();
to
function _fetch_object()
{
if ( is_array($this->pdo_results) ) {
$i = $this->pdo_index;
$this->pdo_index++;
if ( isset($this->pdo_results[$i])) {
$back = new stdClass();
foreach ( $this->pdo_results[$i] as $key => $val ) {
$back->$key = $val;
}
return $back;
}
return null;
}
return $this->result_id->fetch(PDO::FETCH_OBJ);
}
This worked for me. Again, not my work, credit goes out to S. Stüvel, J. Bransen and S. Timmer.
Rather long answer, but i hope this helps.

There is a bug in CodeIgniter version 2.1.0 for PDO drivers (They had just added PDO driver in version 2.1.0)
You can see change log for version 2.1.1
Please try upgrading your CodeIgniter.

I have Codeigniter 2.2.1 and when I set application/config/database.php the same as OP I can use sqlite database, sort of. I can create new database/file, create new tables and insert data. The problem is that I can't read any.
$query = $this->db->get('table_name');
return $query->result_array();
Returns empty array. The same happens when I do.
$query = $this->db->query("SELECT...");
Apparently there are still some bugs. I'm just starting to explore Codeigniter, but when I switch to mysql the same exact Model works as it should.
For the record, everything on my server is set up OK. I can use my sqlite databases just fine, it is just Codeigniter that has problems.

I applied g_m solution after updating from 2.1.3 to 2.2.6, and as jimmy, I had to remove the first change in pdo_driver.php to make it work.

Related

Database Syntax error Codeigniter Grocery Crud with SQLite

I have created one application with Codeigniter Grocery Crud with SQLite. It is working fine at localhost. But when I hosted online by CPanel, it shows syntax error following,
A Database Error Occurred
Error Number: HY000/1
near "SHOW": syntax error
SHOW COLUMNS FROM 'epaper'
Filename: models/Grocery_crud_model.php
Line Number: 436
At File: models/Grocery_crud_model.php 436 line is following
foreach($this->db->query("SHOW COLUMNS FROM '$this->table_name' ")->result() as $db_field_type)
And Full Model is
function get_field_types_basic_table()
{
$db_field_types = array();
foreach($this->db->query("SHOW COLUMNS FROM '$this->table_name' ")->result() as $db_field_type)
{
$type = explode("(",$db_field_type->Type);
$db_type = $type[0];
if(isset($type[1]))
{
if(substr($type[1],-1) == ')')
{
$length = substr($type[1],0,-1);
}
else
{
list($length) = explode(" ",$type[1]);
$length = substr($length,0,-1);
}
}
else
{
$length = '';
}
$db_field_types[$db_field_type->Field]['db_max_length'] = $length;
$db_field_types[$db_field_type->Field]['db_type'] = $db_type;
$db_field_types[$db_field_type->Field]['db_null'] = $db_field_type->Null == 'YES' ? true : false;
$db_field_types[$db_field_type->Field]['db_extra'] = $db_field_type->Extra;
}
$results = $this->db->field_data($this->table_name);
foreach($results as $num => $row)
{
$row = (array)$row;
$results[$num] = (object)( array_merge($row, $db_field_types[$row['name']]) );
}
return $results;
}
For More Reference
https://github.com/scoumbourdis/grocery-crud/blob/master/application/models/Grocery_crud_model.php
Please help me to solve syntax error.

how to implode and insert values into db in codeigniter?

How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.

Codeigniter DataGrid Class

So, I am building myself a simple(ish) datagrid class for my CodeIgniter app.
What I am wondering is, I have some columns that I would like to "format" in that I mean, some may contain only a 1 or a 0, yet I want to turn them into a Yes or No respectively.
How can I do this? In other words, I want to be able to pass in another parameter..something like:
$this->_columnCallBack pass it an array like array(column_number=>'NameOfCallBackFunction')
I am assuming that I would do it somewhat like I did the _columnclass, where I pass in the column number, and the class as an array... but I don't know how I would get the function to fire off to do the replacement...
Code
class O7thDG {
public function __construct($params){
$this->_table = $params['table'];
$this->_pk = $params['pk'];
$this->_fields = (isset($params['fields'])) ? $params['fields'] : null;
$this->_where = (isset($params['where'])) ? $params['where'] : null;
$this->_order = (isset($params['order'])) ? $params['order'] : null;
$this->_extras = (isset($params['extras'])) ? $params['extras'] : null;
$this->_add = (isset($params['add'])) ? $params['add'] : FALSE;
$this->_edit = (isset($params['edit'])) ? $params['edit'] : FALSE;
$this->_delete = (isset($params['delete'])) ? $params['delete'] : FALSE;
$this->_editlink = (isset($params['editlink'])) ? $params['editlink'] : null;
$this->_deletelink = (isset($params['deletelink'])) ? $params['deletelink'] : null;
$this->_editlinkextras = (isset($params['editlinkextras'])) ? $params['editlinkextras'] : null;
$this->_deletelinkextras = (isset($params['deletelinkextras'])) ? $params['deletelinkextras'] : null;
$this->_tableid = (isset($params['tableid'])) ? $params['tableid'] : null;
$this->_tableclass = (isset($params['tableclass'])) ? $params['tableclass'] : null;
$this->_columnclass = (isset($params['columnclass'])) ? $params['columnclass'] : null;
$this->_includeheader = (isset($params['includeheader'])) ? $params['includeheader'] : TRUE;
$this->_allowpaging = (isset($params['allowpaging'])) ? $params['allowpaging'] : FALSE;
$this->_sorting = (isset($params['sorting'])) ? $params['sorting'] : null;
$this->_columncallback = (isset($params['columncallback'])) ? $params['columncallback'] : null;
}
public function BuildIt($responsive = TRUE){
$_ci =& get_instance();
$_ci->load->database();
$_ci->load->library('table');
$_ci->load->library('TKCommon', null, 'comm');
$fldlist = $this->_buildSelectFieldList();
$_ci->db->select($fldlist);
$cols = $this->_buildColumnFieldList();
$ret = '';
if($this->_where != null){
// build the where
}
if($this->_order != null){
// build the order
}
if($this->_extras != null){
// build the extras
}
// Query the specified table
$qry = $_ci->db->get($this->_table);
if($cols == null){
$cols = $_ci->db->list_fields($this->_table);
$fldlist = $cols;
}else{
$fldlist = explode(', ', $fldlist);
}
if($qry){
// throw the results into an associative array
$rs = $qry->result_array();
if($rs){
$rCt = count($rs);
$cCt = $qry->num_fields();
// add our responsive wrapper
if($responsive){
$ret .= '<div class="table-responsive">';
}
// fire up our table
$tid = '';
$tc = '';
if($this->_tableid != null){$tid = ' id="' .$this->_tableid . '"';}
if($this->_tableclass != null){$tc = ' class="' .$this->_tableclass . '"';}
$_ci->table->set_template(array('table_open'=>'<table' . $tid . $tc . '>'));
// build our header row, but only if we need to
if($this->_includeheader && $cCt > 0){
// see if we need to include the admin column
if($this->_edit || $this->_delete){
$_ci->table->set_heading(array_merge($cols, array('Admin')));
}else{
$_ci->table->set_heading($cols);
}
}
// build each records row
for($r = 0; $r < $rCt; ++$r){
$ca = array();
for($c = 0; $c < $cCt; ++$c){
if(($this->_columnclass != null) && ($c == key($this->_columnclass))){
// figure out which column needs the class, and what class needs to be applied
$ca[] = $this->_columnCallback($c, array('data'=>$rs[$r][$fldlist[$c]], 'class'=>$this->_columnclass[key($this->_columnclass)]));
}else{
$ca[] = $this->_columnCallback($c, $rs[$r][$fldlist[$c]]);
}
}
// see if we need to include the admin column
if(($this->_edit || $this->_delete) && ($this->_editlink != null || $this->_deletelink != null)){
$txt = '';
if($this->_edit &&($this->_editlink != null)){
$txt .= '<span class="fa fa-pencil fa-lg"></span> ';
}
if($this->_delete &&($this->_deletelink != null)){
$txt .= '<span class="fa fa-trash-o fa-lg"></span>';
}
if(($this->_columnclass != null) && ($cCt == key($this->_columnclass))){
$ca[] = array('data'=>$txt, 'class'=>$this->_columnclass[key($this->_columnclass)]);
}else{
$ca[] = $txt;
}
}
$_ci->table->add_row($ca);
}
$ret .= $_ci->table->generate();
// close our responsive wrapper
if($responsive){
$ret .= '</div>';
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
return $ret;
}
// build our select's field list
private function _buildSelectFieldList(){
if($this->_fields == null){
return '*';
}else{
$flds = array_map(function($item){return $item['field'];}, $this->_fields);
return implode(', ', $flds);
}
}
// build our tables column list
private function _buildColumnFieldList(){
if($this->_fields == null){
return null;
}else{
return array_map(function($item){return $item['label'];}, $this->_fields);
}
}
private function _columnCallback($col, $val){
if($this->_columncallback != null){
if($col == key($this->_columncallback))
return $this->_columncallback[key($this->_columncallback)]($val);
}else{
return $val;
}
}
}
and my external function that I may want to use is simply:
// Format boolean value to Yes or No
public function YesNo($val){
return ((bool)$val) ? 'Yes' : 'No' ;
}
CI Documentation for the table class has $this->table->function, however, the function(s) passed applies to the entire table
What about using and/or anonymous functions:
http://docs.php.net/manual/es/function.func-get-args.php
http://php.net/manual/en/functions.anonymous.php
Update 2 "reloaded"
You could also check grocery crud, it's CI library and do some interesting things that can be useful for you project:
http://www.grocerycrud.com/
Grocery crud uses call_user_func from PHP and allows you to use any function declaread in your controller, if this is what you need then it's just matter of time and check grocery crud code.
In the library a protected property is declared for each callback for example (line #3386 v1.4.1):
/* Callbacks */
protected $callback_before_insert = null;
So you/me/any can set the callback function in case is needed, then check for any callback setted doing something like (line #878 GroceryCrud 1.4.1):
if($this->callback_before_insert !== null)
{
$callback_return = call_user_func($this->callback_before_insert, $post_data);
if(!empty($callback_return) && is_array($callback_return))
$post_data = $callback_return;
elseif($callback_return === false)
return false;
}
Of course there's a method to set the callback (line #4518 from v1.4.1):
public function callback_before_insert($callback = null)
{
$this->callback_before_insert = $callback;
return $this;
}
And the user/dev set the callback doing:
$crud->callback_before_insert(array($this,'my_callback'));
And/Or this technique allows you use something like:
$this->load->model('Customers');
$crud->callback_before_insert(array($this->Customers,'getCustomersCallback'));
even if you're usign php 5.3 or greater you can use an anonymous method:
$crud->callback_before_insert(function($post_array){
$post_array['user_id'] = $this->session->userdata('user_id');
return $post_array;
});
More info: http://www.grocerycrud.com/documentation/tutorial_using_callbacks
About Grocery Crud:
Author: John Skoumbourdis (more about author/library)
Web: GroceryCrud
License: released with dual licensing, using the GPL v3 and the MIT license.
Update 3
Update I've read more carefully your question, thinking functions varible can work for you:
http://php.net/manual/es/functions.variable-functions.php
See the first and second samples here: http://www.php.net/manual/en/language.oop5.php
Still don't know if they will work "outside" your class, but it could.
These functions will work as you want to, but you need to rewrite a bit for your needs.
function callback1($array, $row_id, $function)
{
if(function_exists($function))
return $function($array[$row_id]);
else
return 0;
}
function YesNo($val)
{
return intval($val) ? 'Yes' : 'No' ;
}
#example of array and usage of script.
$array = array('id' => '0', 'id2' => '1');
$ok = callback1($array, 'id2', 'YesNo');
Make filters array
$this->filters = ['column_name' => 'function_name', 'column_name2' => 'otherFunction'];
Then you just apply the filter to the data
if ( array_key_exists($column_name, $this->filters) ) {
// Add row that contains filtered data
$row_data = $this->filters[$column_name]($column_val);
}else{
$row_data = $column_val;
}
If your functions aren't available globally (not in a helper or built-in php), you'll have to use something like this:
call_user_func(array($this, $this->filters[$column_name]), $column_val);
OR
$this->{$this->filters[$column_name]}($column_val);
This would run a function from inside the library O7...

CodeIgniter - Active Query fails unless I slow it down with garbage on screen. Why?

This is where I am having a problem in CodeIgniter.
My function get_applicable_menu_xml() calls deals_sorting_counts_deal() which does a complex query to get a result set. The num_rows() of that set is returned to be used when generating an XML string for later use in outputting a drop down selector.
For some reason, this fails, appearing to display a blank screen which never stops loading.
But, even stranger if I un-comment the line //print $this->db->last_query(); from just before I return the num_rows(), the code works.
And, YES, I know it's normal to get all kinds of 'Cannot modify header information - headers already sent by...' messages along with the SQL used, but with that the page loads, the numbers all get returned, etc. Without it, the page does NOT load and appears to fail to finsih connecting as if the server is not responding.
My question: what could possibly cause that to happen?
I've spent days trying to debug this.
Note as well, this does not happen on my local WAMP server, or on the Rackspace Linux server for the DEV/QA sites. It ONLY happens on the Rackspace Linux server where the live site is hosted. I've looked around, but cannot find any specific setting that is different that may explain its unique behavior. But, I'm not a Linux server expert. I'm just a competent user.
Firebug is no help as the page isn't loading far enough for anything to show.
Can anyone provide a reasoning behind this odd behaviour?
Thanks,
Al Pieroway
//from my database.php file (but i've played with all these)
$db['default']['pconnect'] = FALSE;
$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'] = FALSE;
//the meat of the problem these functions are in
//my models/general_model.php file
function get_applicable_menu_xml($city_sef,$btype_sef,$search_id,$days,$time,$offset,$perpage,$sort_type,$emp_lat,$emp_long,$radius=30,$merchant_list)
{
$xml = "<menu>";
$parent_cats = $this->db->query("SELECT * FROM `business_type` WHERE `btype_parent` = 0");
foreach($parent_cats->result_array() as $parent_cat)
{
$cat_count = $this->deals_sorting_counts_deal($city_sef,$parent_cat['btype_sef'],$search_id,$days,$time,$offset,$perpage,$sort_type,$emp_lat,$emp_long,$radius,$merchant_list);
$sub_cats = $this->db->query("SELECT * FROM `business_type` WHERE `btype_parent` = ".$parent_cat['btype_id']);
if($sub_cats->num_rows()>0) {
$xml .= "<category id='".$parent_cat['btype_id']."' name='".htmlentities($parent_cat['btype_name'], ENT_QUOTES)."' btype-sef='".$parent_cat['btype_sef']."' count='".$cat_count."'>";
foreach($sub_cats->result_array() as $sub_cat)
{
$sub_cat_count = $this->deals_sorting_counts_deal($city_sef,$sub_cat['btype_sef'],$search_id,$days,$time,$offset,$perpage,$sort_type,$emp_lat,$emp_long,$radius,$merchant_list);
$xml .= "<subcategory id='".$sub_cat['btype_id']."' name='".htmlentities($sub_cat['btype_name'], ENT_QUOTES)."' btype-sef='".$sub_cat['btype_sef']."' count='".$sub_cat_count."'></subcategory>";
}
$xml .= "</category>";
}
}
$xml .= "</menu>";
return '<?xml version="1.0" encoding="UTF-8"?>'.$xml;
}
function deals_sorting_counts_deal($city_sef,$btype_sef,$search_id,$days,$time,$offset,$perpage,$sort_type,$emp_lat,$emp_long,$radius=30,$merchant_list)
{
$sql11 = 'SET OPTION SQL_BIG_SELECTS = 1';
$this->db->query($sql11);/**/
$today = substr(date('l',mktime(0,0,0)),0,3);
if ($today=='Mon') { $day_to = 1; }
elseif($today=='Tue') { $day_to = 2; }
elseif($today=='Wed') { $day_to = 3; }
elseif($today=='Thu') { $day_to = 4; }
elseif($today=='Fri') { $day_to = 5; }
elseif($today=='Sat') { $day_to = 6; }
elseif($today=='Sun') { $day_to = 7; }
$string_IN ='';
if($btype_sef!='all') {
$string_IN .= $btype_sef.",";
$next_id = 0;
$this->db->select('btype_id');
$this->db->from('business_type');
$this->db->where('btype_sef',$btype_sef);
$result_id = $this->db->get();
if($result_id->num_rows()>0)
{
$row_id = $result_id->row();
$next_id = $row_id->btype_id;
$this->db->select('btype_sef');
$this->db->from('business_type');
$this->db->where('btype_parent',$next_id);
$result_str = $this->db->get();
if($result_str->num_rows()>0)
{
foreach($result_str->result_array() as $result_s)
{
$btype_sef_shild = $result_s['btype_sef'];
$string_IN .= $btype_sef_shild.",";
}
}
}
$string_IN = substr($string_IN,0,-1);
$IN_ARRAY = explode(',',$string_IN);
}
if($this->session->userdata('emp_lat')!='' and $this->session->userdata('emp_long')!='') {
$fLat = $emp_lat;
$fLon = $emp_long;
}
else {
$fLat = $emp_lat;
$fLon = $emp_long;
}
$this->session->set_userdata('emp_long',$emp_long);
$com_id = $this->session->userdata('comp_id');
$this->db->select('vendor.longitude,vendor.latitude,deals.is_time,deals.deal_img,deals.deal_avilable_custom,vendor.vendor_desc,deals.status_id as check3 ,deal_company.deal_id as deal_id,deal_company.comp_id as cmp, vendor.vendor_image,vendor.vendor_id,vendor.vendor_city_id,vendor.vendor_business_type_id,vendor.vendor_state_id,vendor.vendor_business_name,deals.start_date_time,deals.end_date_time,deals.deal_id,dtype_id,deal_name,deal_detail,deals.terms,deals.status_id,deal_sef,hero_emp_id,hero_comp_id,business_type.btype_name,deal_availabe.available_id');
$this->db->from('deals');
$this->db->join('vendor','vendor.vendor_id=deals.vendor_id');
$this->db->join('business_type','vendor.vendor_business_parent_type_id=business_type.btype_id OR vendor.vendor_business_child_type_id=business_type.btype_id OR vendor.vendor_business_parent_type_id1=business_type.btype_id OR vendor.vendor_business_child_type_id1=business_type.btype_id OR vendor.corporate_parent_category_id=business_type.btype_id OR vendor.corporate_child_category_id=business_type.btype_id' );
$this->db->join('deal_availabe','deal_availabe.deal_id=deals.deal_id');
$this->db->join('deal_company','deal_company.deal_id=deals.deal_id');
$this->db->where('deal_company.comp_id',$com_id);
$this->db->where('vendor.status_id',1);
if ($search_id!='')
{
$term = $this->db->escape_like_str(strip_tags($search_id));
$this->db->where("(deals.deal_name LIKE '%{$term}%' OR vendor.vendor_business_name LIKE '%{$term}%')");
}
if($btype_sef!='all')
{
if($string_IN=='')
{
$this->db->where('business_type.btype_sef',$btype_sef);
}
else
{
$this->db->where_in('business_type.btype_sef', $IN_ARRAY);
}
}
if($days!='all')
{
$this->session->set_userdata('day_check',$days);
$this->db->where('deal_availabe.available_id',$days);
}
else
{
$this->session->set_userdata('day_check','');
}
if($time!='all')
{
$this->db->where('deal_timeofday.tod_id',$time);
}
if($city_sef!='' && $city_sef!='all')
{
$names = array(0, $city_sef);
}
else
{
$names = array(0, 1);
}
$this->db->where('deals.status_id',1);
$date_starting = time();
$this->db->where('end_date_time >=', $date_starting);
$this->db->where('start_date_time <=', $date_starting);
$this->db->group_by('deals.deal_id');
$this->db->order_by('deals.is_feature','asc');
$this->db->limit($perpage,$offset);
$result = $this->db->get() or die("huh");
//print $this->db->last_query();
return $result->num_rows();
}

Switching databases in code igniter

I have two databases I need to connect to, which I can do in the controllers and libraries I have written. For some odd reason (i'm assuming I'm just missing something simple here) I can't get it to work in the model all of the sudden. I have read the database class in the CI user guide.
I tried making a reference to $pew when loading pew ($this->pew =& $this->load->database('pew', TRUE)) to no avail.
Any thoughts, suggestions? Thanks!
Error
PHP Fatal error: Call to a member function query() on a non-object in
/Sites/CI/nyan/application/models/pewpewmodel.php on line 15
Line 15
$this->pew->query('SELECT * FROM ExtractEvent'); //simplified for testing
database.php:
$active_group = 'nyan';
$active_record = TRUE;
$db['nyan']['hostname'] = 'catcatcat';
$db['nyan']['username'] = 'mew';
$db['nyan']['password'] = 'meow';
$db['nyan']['database'] = 'meow';
$db['nyan']['dbdriver'] = 'mysql';
$db['pew']['hostname'] = 'jujubees';
$db['pew']['username'] = 'qwop';
$db['pew']['password'] = 'qwop';
$db['pew']['database'] = 'nom';
$db['pew']['dbdriver'] = 'mssql';
Model pewpewmodel.php
private $pew;
function __construct()
{
parent::__construct();
$this->pew = $this->load->database('pew', TRUE);
}
function get_forms_by_date($id = NULL, $Year = NULL, $Month = NULL, $Day = NULL)
{
$this->pew->query('SELECT * FROM ExtractEvent'); //simplified for testing
}
Controller nomnom.php
public function index()
{
$this->load->model('pewmodel');
$data['Forms'] = $this->pewmodel->get_forms_by_date($this->session->userdata('Username'), date('Y'), date('n'), date('j'));
$this->load->view('common/header', $data['Forms']);
$this->load->view('home/index');
$this->load->view('common/footer');
}
View index.php
<pre>
<?php print_r($Forms); ?>
</pre>
This worked for me.
[from within the model constructor]
$db['hostname'] = 'localhost';
$db['username'] = 'root';
$db['password'] = '';
$db['database'] = 'my_database';
$db['dbdriver'] = 'mysql';
$db['dbprefix'] = '';
$db['pconnect'] = TRUE;
$db['db_debug'] = TRUE;
$db['cache_on'] = FALSE;
$db['cachedir'] = '';
$db['char_set'] = 'latin1';
$db['dbcollat'] = 'latin1_bin';
$db['swap_pre'] = '';
$db['autoinit'] = TRUE;
$db['stricton'] = FALSE;
$this->load->database($db, FALSE, TRUE);
// False=don't return db object
// True =use as active record, so it replaces default $this->db
Hope this helps coders searching through Google like I did.
$this->pew = $this->load->database('pew', TRUE);
You load a database which doesn't exist in your database-configuration.
I was getting a 500 error when I passed TRUE to connect like below. I assumed (yeah I know) that I was just having the same problem with connecting. truth be told it was an ID10T error from the beginning. I was missing the mssql.so library on my local machine and another I was testing from.
$this->pew =& $this->load->database('pew', TRUE)
My apologies for the waste of time gents.

Categories