Switching databases in code igniter - php

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.

Related

PHP 5.3.10 SoapServer::handle not finding function

I am getting this error in Apache2 errors logs:
PHP Fatal error: Function 'ns1:getClients' doesn't exist
I checked to see why the PHP Soap Server is not locating the method in the class Client_API and can't see any course here's the index.php file:
require(INCLUDES_DIR.'BaseService.class.php');
require($interfaceFile);
require($serviceFile); // loads /var/www/official-productionapi/includes/Client.service.php
//...
$server = new SoapServer(null, array ('uri'=>'', 'trace' => 1, 'connection_timeout' => intval(600)));
$server->setClass($serviceName.CLASS_SUFFIX); // -- e.g. 'Client_API'
$server->handle();
The Class containing the missing method:
class Client_API extends BaseService implements Client_API_Interface
{
public function getClients($range = 10, $search, $accessUserID = null)
{
if(!$this->Authenticated){
throw new SoapFault('Server', 'Authorization failed: Wrong username or password');
}
$max = 100;
$range = (int)$range;
if($range > $max){
$range = $max;
}
$clients = array();
$db = Database::getInstance();
if(null !== $accessUserID){
$sql = "SELECT * FROM clients as c, users_clients_access as uac WHERE c.ClientID = uac.ClientID AND uac.UserID = '".$db->escape($accessUserID)."' AND c.IsShopAssistClient = 0 AND (c.ClientName LIKE '".$db->escape($search)."%' OR c.Tag LIKE '".$db->escape($search)."%') ORDER BY c.ClientName Asc LIMIT $range";
}else{
$sql = "SELECT * FROM clients WHERE IsShopAssistClient = 0 AND (ClientName LIKE '".$db->escape($search)."%' OR Tag LIKE '".$db->escape($search)."%') ORDER BY ClientName Asc LIMIT $range";
}
$clientQ = $db->query($sql);
while($client = $db->fetch_array($clientQ)){
$arr = array();
$arr['PClientName'] = $client['ClientName'];
$arr['PClientTag'] = $client['Tag'];
$clients[$client['ClientID']] = $arr;
}
return $clients;
}
//...
Any help would be appreciated, I have been thinking if it has something to do with PHP version mismatch, it was working on version 5.3.3 but it's not on version 5.3.10. So only minor differences.
I have been able to solve this issue by setting uri option to 'uri'=>'api'. Seems like leaving it blank wasn't a good idea. It still boggles me how it works on the same version of PHP on Windows just fine.
This post led me to my answwer: Issues with SOAP in non-WSDL mode.

Yii2 ActiveRecord Setting unknown property: app\models\

This code throw Exception:
public function actionSetdubl() {
$dubls = Yii::$app->request->post('dubl');
$parent = Yii::$app->request->post('parent');
$parentInfo = JurForm::find()->where(['PKJUR' => $parent])->asArray()->all()[0];
for ($i = 0; $i < sizeof($dubls); ++$i) {
$val = $dubls[$i];
$jur = JurForm::findOne($val);
$jur->CFLDUBL = 'Yes';
$jur->DUBLMDM_ID = $parentInfo['MDM_ID'];
$jur->DCHANGEDATE = date('Y-m-d H:i:s');
$jur->save();
}
return Yii::$app->getResponse()->redirect('/index.php?r=jur/analysis');
}
on the line with code $jur = JurForm::findOne($val);.
Exception:
Setting unknown property: app\models\JurForm::PKJUR.
DB: Oracle.
ActiveRecord2 has a hard time automatically mapping table names that start with a capital letter.
So for these columns you have to go into your model class and formally declare them:
public $PKJUR;
maybe better?
$parentInfo = JurForm::find()->where(['PKJUR' => $parent])->asArray()->one()
also i think PKJUR is not defined in DB.

CodeIgniter Sqlite not working

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.

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

PHP classes are keeping me from accessing the needed variable

ok so i have a php file that includes code for do a sql insert
myfile.php
include($somewhere.'/addleads.php');
addleads.php
require_once(MAIN_CLASS_PATH."common/class.Common.php");
require_once(MAIN_CLASS_PATH."modules/Leads/class.Leads.php");
$objcommon = new common();
$objLeads = new Leads();
$Errormsg = $objLeads->AddLBCleads($_REQUEST);
class.Leads.php
class Leads extends Common{
function Leads(){
$this->Common();
$this->Leadstype = "Leadstype";
$this->Leads = "Leads";
}
function AddLBCleads($objArray){
global $_REQUEST,$objSmarty,$global_config;
$objLeads = new Leads();
$objInsertArray['txtP_Ident'] = $objArray['selProperty'];
$objInsertArray['txtFirstName'] = $objArray['txtfirstname'];
$objInsertArray['txtLastName'] = $objArray['txtlastname'];
$objInsertArray['txtEmail'] = $objArray['txtEmail'];
$objInsertArray['txtPhone'] = $objArray['txtPhone'];
$objInsertArray['txtTypeId'] = $objArray['selleadtype'];
$objInsertArray['txtComments'] = $objArray['txtcomments'];
$StrEnterdate = date('Y-m-d H:i:s');
$objInsertArray['txtMoveDate'] = $StrMoveDate;
$objInsertArray['txtEntereddate'] = $StrEnterdate;
$current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
How do i get $current_id from myfile.php, when i try to access it is unavailable
Just below this line:
class Leads extends Common{
Add:
public $current_id = null; // create a public accessible variable
And instead of:
$current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
Use:
$this->current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
Now you can get it like:
$objLeads = new Leads();
echo $objLeads->current_id;

Categories