For some weird reason when i attempt to load the database no results are being returned.
class Customer_model extends CI_Model {
public function fetch_email_list() {
$DB1 = $this->load->database('orders', TRUE);
if ( $this->load->database('orders') === FALSE ){
echo 'no database';
}
$results = $DB1->query("SELECT * FROM email_list");
return $results->result_array();
}
}
I've checked my database config
$db['orders']['hostname'] = 'localhost';
$db['orders']['username'] = 'db_user';
$db['orders']['password'] = 'password';
$db['orders']['database'] = 'db_name';
$db['orders']['dbdriver'] = 'mysql';
$db['orders']['dbprefix'] = '';
$db['orders']['pconnect'] = FALSE;
$db['orders']['db_debug'] = TRUE;
$db['orders']['cache_on'] = FALSE;
$db['orders']['cachedir'] = '';
$db['orders']['char_set'] = 'utf8';
$db['orders']['dbcollat'] = 'utf8_general_ci';
$db['orders']['swap_pre'] = '';
$db['orders']['autoinit'] = TRUE;
$db['orders']['stricton'] = FALSE;
How do i solve?
No database is added in database.php. And this use $DB1 = $this->load->database('orders', TRUE); for if we have multiple Databases only.
Set default DB
$db['orders']['database'] = 'orders';
In Code
public function fetch_email_list() {
$this->load->database();
$query = $this->db->query("SELECT * FROM email_list");
$result = $query->result_array();
return $result
}
Codeigniter - multiple database connections
You may define the database instance globally in a model so you can access it across methods as follows:
class Some_model extends CI_Model {
// Our 2nd database
protected $DB2;
public function __construct () {
parent::__construct();
$this->DB2 = $this->load->database('orders', TRUE);
}
public function some_method () {
$q = $this->DB2->query('...');
}
public function some_other_method () {
$q = $this->DB2->query('...');
}
}
Try this
$query = $this->db->get('email_list');
return $query->result_array();
Related
i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.
My English is not good so sorry for any mistake. I'm new to Codeigniter, I am trying to search record by using this code, this is my controller code:
public function search() {
if(isset($_POST['search']))
{
$s = $_POST['search'];
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name =' ,"{$s}" );
$query = $this->db->get();
$res = $query->result();
$data['user'] = null ;
if($res)
{
$data['user'] = $res ;
}
$this->load->view('filter' , $data);
}
}
It is working fine but I want to write this code in separate Model.
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name =' ,"{$s}" );
$query = $this->db->get();
$res = $query->result();
But i don't know how to pass this variable value $s = $_POST['search']; to my model. Any suggestion?
you can try the following
//in your application/models Folder put a File called UserSearch_Model.php
class UserSearch_Model extends CI_Model
{
public function search($strSearch)
{
$query = $this->db
->select('u_id,name,email,phone')
->from('user')
->where('name' ,$s)
->get();
return $query->result();
}
}
//and in your controller
public function search()
{
$strSearch = $this->input->post('search');
if (!empty($strSearch))
{
$data = [];
$this->load->model("UserSearch_Model");
$data['user'] = $this->UserSearch_Model->search($strSearch);
if (is_array($data['user']) && count($data['user']) > 0)
{
$this->load->view('filter' , $data);
}
}
}
You can try this solution for your problem :
public function search() {
$search_value = $this->input->post('search'));
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
if (isset($search_value) && !empty($search_value)) {
$this->db->where('name',$search_value);
// OR
$this->db->like('name', $search_value);
}
$query = $this->db->get();
$res = $query->result();
$data['user'] = null;
if ($res) {
$data['user'] = $res;
}
$this->load->view('filter', $data);
}
I hope it will help.
Controller
public function search() {
$search = $this->input->post('search');
$this->load->model('your_model'); //<-- You can load the model into "__construct"
$search_result = $this->your_model->your_search_function($search); //<-- This is how you can pass a variable to the model from controller
$this->load->view('your_view',['search_result'=>$search_result]); //<-- This is how you can load the data to the view. Hear your search result array is loaded on your view
}
Model
public function your_search_function($search) {
//You will receive this search variable ^^ here in your model
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name',$search);
$query = $this->db->get();
$result = $query->result_array();
if(isset($result) && !empty($result))
{
return $result;
} else
{
return FALSE;
}
}
I am trying to add a separate report database to my application by extending CI_Model and setting up the correct database to use based on if the database is defined. The report database will be a replicated version of the regular database for performance reasons.
Is this the proper way?
In application/core/MY_Model:
<?php
class MY_Model extends CI_Model
{
function __construct()
{
parent::__construct();
include APPPATH.'config/database.php';
//If we have a reporting database load it and use it for all reporting functions
if (isset($db['reports']))
{
$this->report_db = $this->load->database('reports', TRUE);
}
else
{
$this->report_db = $this->load->database('default', TRUE);
}
}
}
?>
You can use both of your databases within your code. This you have to define in config/database.php
database.php
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'username';
$db['default']['password'] = 'password';
$db['default']['database'] = 'database1';
$db['default']['dbdriver'] = 'mysqli';
$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;
$db['reports']['hostname'] = 'localhost';
$db['reports']['username'] = 'username';
$db['reports']['password'] = 'password';
$db['reports']['database'] = 'database2';
$db['reports']['dbdriver'] = 'mysqli';
$db['reports']['dbprefix'] = '';
$db['reports']['pconnect'] = TRUE;
$db['reports']['db_debug'] = TRUE;
$db['reports']['cache_on'] = FALSE;
$db['reports']['cachedir'] = '';
$db['reports']['char_set'] = 'utf8';
$db['reports']['dbcollat'] = 'utf8_general_ci';
$db['reports']['swap_pre'] = '';
$db['reports']['autoinit'] = TRUE;
$db['reports']['stricton'] = FALSE;
reports_model.php
<?php
class Reports_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->db_reports = $this->load->database('reports', TRUE);
}
public function reports_list()
{
$this->db_reports->get('some_table');
}
}
other_model.php
<?php
class Other_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function xyz()
{
$this->db->get('some_table');
}
}
Explanation:
Since you have defined default as your active group, so whatever database you have defined in your default group, you can use as following in your model -
$this->db->get('some_table'); // as we defined normally
And sine you have other databases also you can have another group of them. We have defined them in reports group. So we have add an extra _reports after db like this -
$this->db_reports->get('some_table');
I am junior of codeigniter, what I want to do is connect multiple database to retrieve the database data, but it is not working for me, keep return me 404 error page
here is my code
config/database.php
$active_group = 'qm';
$active_record = TRUE;
$db['qm']['hostname'] = '192.168.0.128';
$db['qm']['username'] = 'callcenter';
$db['qm']['password'] = 'ca11c3nt3r';
$db['qm']['database'] = 'qm';
$db['qm']['dbdriver'] = 'mysql';
$db['qm']['dbprefix'] = '';
$db['qm']['pconnect'] = TRUE;
$db['qm']['db_debug'] = TRUE;
$db['qm']['cache_on'] = FALSE;
$db['qm']['cachedir'] = '';
$db['qm']['char_set'] = 'utf8';
$db['qm']['dbcollat'] = 'utf8_general_ci';
$db['qm']['swap_pre'] = '';
$db['qm']['autoinit'] = TRUE;
$db['qm']['stricton'] = FALSE;
/* call contact detail table */
$active_group = "reportcallcenter";
$active_record = TRUE;
$db['reportcallcenter']['hostname'] = '192.168.0.128';
$db['reportcallcenter']['username'] = 'callcenter';
$db['reportcallcenter']['password'] = 'ca11c3nt3r';
$db['reportcallcenter']['database'] = 'reportcallcenter';
$db['reportcallcenter']['dbdriver'] = 'mysql';
$db['reportcallcenter']['dbprefix'] = "";
$db['reportcallcenter']['pconnect'] = TRUE;
$db['reportcallcenter']['db_debug'] = TRUE;
$db['reportcallcenter']['cache_on'] = FALSE;
$db['reportcallcenter']['cachedir'] = "";
$db['reportcallcenter']['char_set'] = "utf8";
$db['reportcallcenter']['dbcollat'] = "utf8_general_ci";
$db['reportcallcenter']['swap_pre'] = '';
$db['reportcallcenter']['autoinit'] = TRUE;
$db['reportcallcenter']['stricton'] = FALSE;
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Qm extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->permission->is_logged_in();
//load model
$this->load->helper('url');
$this->load->model('callcontactsdetails_model');
$this->load->database('qm', TRUE);
$this->load->database('reportcallcenter', TRUE);
}
function qm_form()
{
$data = array();
$data['page'] = 'qm_form';
if($query = $this->callcontactsdetails_model->get_all())
{
$data['recordings_record'] = $query;
}
$data['main'] = 'qm/qm_form';
$data['js_function'] = array('qm');
$this->load->view('template/template',$data);
}
}//end of class
?>
Model (I using My_model)
<?php
class Callcontactsdetails_model extends MY_Model {
protected $_table = 'callcontactsdetails';
protected $primary_key = 'id';
}
?>
My Screen Return Result
Any Idea how to solve my problem or any mistake I did ?
Load your database like this
$this->db_report = $this->CI->load->database('reportcallcenter', TRUE);
assumed that 'qm' db will be set as default
or you can try like this
$DB1 = $this->load->database('qm', TRUE);
$DB2 = $this->load->database('reportcallcenter', TRUE);
then you can use like
$DB1->query();
$DB1->result();
and
$DB2->query();
$DB2->result();
in your case try like
if($query = $DB2->get_all())
{
$data['recordings_record'] = $query;
}
This is my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Order extends CI_Controller {
public function index($id=-1) {
$this->load->model('order');
}
}
When i try to open the corresponding url i get Error 500. The strange thing is that i load the model the same way on another controller without a problem.
Here goes the route and the model just in case:
Route:
$route['order/(:num)'] = "order/index/$1";
Model:
<?php
class Order extends CI_Model {
var $fullname = '';
var $email = '';
var $address = '';
var $phone = '';
var $notes = '';
var $facebook = '';
//var $canvases = '';
var $admin_notes = '';
var $status = '';
var $id = '';
var $date = '';
var $price = '';
//var $emailStatus_recivedOrder = '';
//var $emailStatus_sendedOrder = '';
//var $emailStatus_askFeedback = '';
function __construct() {
// Call the Model constructor
parent::__construct();
}
function get($search_query='', $per_page=5, $skip=0) {
if($search_query != '') {
$this->db->or_where('id', $search_query);
$this->db->or_where('email', $search_query);
$this->db->or_where('fullname', $search_query);
$this->db->or_where('phone', $search_query);
}
$query = $this->db->get('entries', $per_page, $skip);
return $query->result();
}
function count_all($search_query='') {
if($search_query != '') {
$this->db->or_where('id', $search_query);
$this->db->or_where('email', $search_query);
$this->db->or_where('fullname', $search_query);
$this->db->or_where('phone', $search_query);
}
$this->db->from('entries');
return $this->db->count_all_results();
}
function get_by_id($id) {
return $this->db->get_where('entries', array('id' => $id), 1);
}
function get_active_orders_count() {
$this->db->where('status', '1');
$this->db->from('entries');
return $this->db->count_all_results();
}
function insert_entry() {
$this->fullname = $this->input->post('fullname');
$this->email = $this->input->post('email');
$this->address = $this->input->post('address');
$this->phone = $this->input->post('phone');
$this->facebook = $this->input->post('facebook');
$this->notes = $this->input->post('notes');
$this->admin_notes = $this->input->post('admin_notes');
$this->status = $this->input->post('status');
$this->date = date('Y-m-d H:i:s');
$this->db->insert('entries', $this);
}
function update_entry() {
$this->admin_notes = $this->input->post('admin_notes');
$this->db->update('entries', $this, array('id' => $this->input->post('admin_notes')));
}
}
The error is:
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346
You can't name your controller and model the same.
give them a different name and the problem should be fixed. So something like
Controller
class Order extends CI_Controller{ ... }
Model
class Order_model extends CI_Model{ ... }
In Objected oriented programming no two class can have the same name. As of codeigniter Controllers, Models are all classes. So, it is good practice to name your controller as ABC_Controller and model as ABC_Model to avoid class name conflict.
Controller
class ABC_Controller extends CI_Controller { .. }
Model
class ABC_Model extends CI_Model { .. }