I have created one new function in a existing controller, in which I am accessing a model's function which has a query to get the list.
I have loaded the model in controller. This model function works with other function but not working for new created function.
class Cart extends CI_Controller
{
function Cart()
{
parent::__construct();
$this->mdl_common->checkUserSession();
$this->load->model('mdl_friend_web');
$this->load->model('api/mdl_friend','mdl_friend_api');
$this->load->model('mdl_cart_web');
$this->load->library('pagination');
}
//works for this function
function ajax_get_cart_list($offset = 0)
{
is_ajax();
$this->load->model('mdl_cart_web');
$limit = PER_PAGE;
$s_data = $_POST;
$carts = $this->mdl_cart_web->get_cart_list($limit,$offset,$s_data)->result_array();
$totalRows = $this->mdl_cart_web->get_total_cart_product($s_data)->num_rows();
$data = $this->mdl_common->pagination_data('cart/get_cart_list/',$totalRows,$limit,'show_data');
$data['carts'] = $carts;
$data['total_cart'] = $totalRows;
$html = $this->load->view('cart/ajax_cart_list',$data,true);
echo $html;
}
//not working for this
function calculate_distance()
{
$limit = '';
$delivery = 0;
$previousName = '';
$count = 0;
$oneShop = '0';
is_ajax();
// $this->load->model('mdl_cart_web');
$lat1 = $_POST['lat1'];
$long1 = $_POST['long1'];
// $user_id = $_POST['user_id'];
$user_id = $this->session->userdata('user_id');
$carts = $this->mdl_cart_web->get_cart_list($limit,0,'')->result_array();
$response = array();
$data['carts'] = $carts;
foreach($data['carts'] as $row) {
echo $row['store_latitude'];
}
}
model
<?php
class Mdl_cart_web extends CI_Model
{
/*=================================================================================
Get cart list
==================================================================================*/
function get_cart_list($limit,$offset,$data)
{
$this->db->select('c.*,p.*,s.name as store_name,s.latitude as store_latitude,s.longitude as store_longitude,count(r.product_id) as review , IFNULL(AVG(r.star),0) as avg_star,i.*',false);
$this->db->join('p_product as p','c.product_id = p.product_id','left');
$this->db->join('p_product_image as i','c.product_id = i.product_id','left');
$this->db->join('p_product_review as r','c.product_id = r.product_id','left');
$this->db->join('p_store as s','s.store_id = p.store_id','left');
$this->db->limit($limit,$offset);
$this->db->where('c.user_id',$this->session->userdata('user_id'));
$this->db->group_by('c.cart_id');
$this->db->from('p_cart as c');
return $this->db->get();
}
?>
I am not able to get the array data.I can see blank alert.
What is going wrong here? Please help.Thank you.
I think you are writing your query not properly try this:
$this->db->select('c.*,p.*,s.name as store_name,s.latitude as store_latitude,s.longitude as store_longitude,count(r.product_id) as review , IFNULL(AVG(r.star),0) as avg_star,i.*',false);
$this->db->from('p_cart as c');
$this->db->join('p_product as p','c.product_id = p.product_id','left');
$this->db->join('p_product_image as i','c.product_id = i.product_id','left');
$this->db->join('p_product_review as r','c.product_id = r.product_id','left');
$this->db->join('p_store as s','s.store_id = p.store_id','left');
$this->db->limit($limit, $offset);
$this->db->where('c.user_id', $this->session->userdata('user_id'));
$this->db->group_by('c.cart_id');
return $this->db->get();
As Above comment and after seeing your question that the model works fine for the one function and not for the other so I think that loading a model is what you have to look properly.
I see that in your not working function you have noticed some basic problems.
You have commented the model loading code after is_ajax(). // $this->load->model('mdl_cart_web'); so first remove that comment and try again.
Send Correct and proper data to the model. Please Check this below line of code that is executing properly or not.
In Your Not working model.
$carts = $this->mdl_cart_web->get_cart_list($limit,0,'')->result_array();
In Your Working Model:
$carts = $this->mdl_cart_web->get_cart_list($limit,$offset,$s_data)->result_array();
And One thing I want if you are using the same model in more functions in the same controller then you should use __construct()
public function __construct() {
parent::__construct ();
$this->load->model('mdl_cart_web');
}
By adding a model into the __construct() you can use it in the entire controller and all of the functions.
Related
Hi i am using foreach in php oops to output data from the mysqlbut each data outputs twice please check my code and help it i have tried but no correct result
Here is the code below i have used
class getdata extends db{
public function getdata(){
$sql = "SELECT * FROM users";
$results = $this->connect()->query($sql);
$numrows = $results->num_rows;
if($numrows > 0){
while($row = $results->fetch_assoc()){
$data[] = $row;
}
return $data;
}
else{
echo 'no values';
}
}
}
class showusers extends getdata{
//show users
public function showusers(){
$datas = $this->getdata();
foreach($datas as $data){
echo $data['id'].'<br>';
echo $data['name'].'<br>';
}
}
}
$showusers = new showusers();
$showusers->showusers();
Don't give your function the same name as your class.
With $showusers = new showusers(); you are already executing the showusers function.
To cite php.net:
For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class.
Source:https://www.php.net/manual/en/language.oop5.decon.php
So your function showusers() is treated as a constructor for your showusers class and therefore is executed twice. Once when you create an object of the class and once when you call the method.
your code is a bit convoluted I'd suggest passing the database connection object rather than extending continiously.
In this case your constructor showUsers() outputs a list of users. therefore it repeats because you are calling this function twice.
$showusers = new showusers(); // prints users
$showusers->showusers(); // prints users again
move your display function
class showusers extends getdata{
$data;
//initialize
public function showusers(){
$this->data = $this->getdata();
}
//show users
public function displayUsers(){
foreach($this->data as $data){
echo $data['id'].'<br>';
echo $data['name'].'<br>';
}
}
}
$showusers = new showusers();
$showusers->displayUsers();
public function ajax_disposisi() {
$this->load->helper('tanggal');
$this->jadwal->column_search=array('nomor','tanggal');
$this->jadwal->column_order=array(null,'nomor','tanggal');
$list = $this->jadwal->get_datatables('v_disposisi_jadwal');
$data = array();
$no = isset($_POST['start'])?$_POST['start']:0;
print_r($list);
}
this code is controller.
v_disposisi_jadwal >> view database.
when I debug the list using 'print_r($list);', but the record don't show all.
please give me some advices..
thanks
class Jadwal_model extends MY_Model {
var $column_order = array(null, 'nomor','awal','akhir','ao','ro','workflow');
var $column_search = array('nomor','awal','workflow');
public function __construct()
{
parent::__construct();
$this->table='v_jadwal';
}
public function get_detail($id, $suffix='')
{
$this->db->where($this->table.$suffix.'.id',$id);
$query=$this->db->get($this->table.$suffix);
return $query->result();
}
}
I've already found the problem solving.
I've found function get_datatables function >> application/core/MY_Model.php
then I see the format how to use get_datatables.
it should be this..
$list = $this->jadwal->get_datatables('v_disposisi_jadwal', '', 'status_id IN(1,2,11)');
My program is not working properly, i do not know what should i do :S
I got this error message:
Take a look at this:
Here is my code:
My controller file (Home):
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Crudmodel");
}
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
if(!empty($user[0]['username'])){
$data[$key]['user_id'] = $user[0]['username'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler
}
if(!empty($subject[0]['name'])){
$data[$key]['subject_id'] = $subject[0]['name'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]["subject_id"] = "";
// or anything you can use as error handler
}
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}
}
?>
Crudmodel:
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM usuarios WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
Dont know what to do now :(
Hope you can help me :S
The problem is in the model. You only return something inside the else. Easy fix, move the return.
You should probably return an empty array if there are no rows. Then the foreach will still have something to work with - even if it is empty. foreach will choke if given something that cannot be used in a loop - a string for instance.
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = array();
}
return $result;
}
I'm using Codeigniter with dynamic subdomains, but in each method of my controllers I need to get the account of the dynamic subdomain. I'm looking for a way to get the domain and add to the $data without to it every method like:
<?php
class Dashboard extends CI_Controller {
function index()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->db->from('accounts')->where('subdomain', $subdomain_name);
$query = $this->db->get();
$account = $query->row();
$data['account_id'] = $account->id;
$data['account_name'] = $account->name;
$this->load->view('index', $data);
}
function clients()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->db->from('accounts')->where('subdomain', $subdomain_name);
$query = $this->db->get();
$account = $query->row();
$data['account_id'] = $account->id;
$data['account_name'] = $account->name;
$this->load->view('clients', $data);
}
}
Do it once within a Class Constructor and then you can access the same variables from all of the other methods.
As per docs:
"Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work."
<?php
class Dashboard extends CI_Controller {
public $data = array();
public function __construct()
{
parent::__construct();
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->db->from('accounts')->where('subdomain', $subdomain_name);
$query = $this->db->get();
$account = $query->row();
$this->data['account_id'] = $account->id;
$this->data['account_name'] = $account->name;
}
public function index()
{
$data = $this->data; // contains your values from the constructor above
$data['title'] = "My Index"; // also use your $data array as normal
$this->load->view('index', $data);
}
public function clients()
{
$data = $this->data; // contains your values from the constructor above
$this->load->view('clients', $data);
}
}
NOTE: Even though CodeIgniter functions default to "public", it's best practice to declare them as such. See: Public functions vs Functions in CodeIgniter
I'm new to Codeigniter and PHP in general, so bear with me.
I'm attempting to use the codeigniter pagination class to paginate the results returned from a query. The code below works fine with static queries that don't require any parameters passing. However, it seems to break down when attempting to pass a variable as a parameter in the URL e.g.
localhost/index.php/termsbyletter/index/a
where 'a' is the $letter variable passed to the controller/model.
PHP isn't outputting any errors and the query performs as expected, as does the record_count function within the model. The result is that all of the query results are displayed, but all on the same page, which stays the same when the pagination links are clicked.
Also, in the model, is there a more efficient way of returning the row count than running the query twice? I've read on here that this is necessary, and I haven't had any success trying to pass this value any other way.
Here is my controller:
<?php
class Termsbyletter extends CI_Controller
{
public function __construct() {
parent:: __construct();
$this->load->helper("url");
$this->load->model("terms_by_letter");
$this->load->library("pagination");
}
public function index($letter) {
$config = array();
$config["base_url"] = base_url() . 'index.php/termsbyletter/index/' . $letter;
$config["total_rows"] = $this->terms_by_letter->record_count($letter);
$config["per_page"] = 3;
$config["uri_segment"] = 5;
$this->pagination->initialize($config);
$page = ($this->uri->segment(5)) ? $this->uri->segment(5) : 0;
$data["results"] = $this->terms_by_letter->term($config["per_page"], $page, $letter);
echo $this->pagination->create_links();
$this->load->view("/templates/header");
$this->load->view("/terms/index", $data);
$this->load->view("/templates/footer");
}
}
and the model:
class Terms_by_letter extends CI_Model
{
public function __construct() {
parent::__construct();
$this->load->database();
}
public function record_count($letter) {
$query = $this->db->query("SELECT * FROM news WHERE LEFT(slug, 1) = '$letter'");
return $query->num_rows();
}
public function term($limit, $start, $letter) {
$this->db->limit($limit, $start);
$query = $this->db->query("SELECT * FROM news WHERE LEFT(slug, 1) = '$letter'");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
}
and I'm using something like this to output the results in the view:
<?php
foreach($results as $data) {
echo $data->slug "<br>";
}
?>
<p><?php echo $links; ?></p>
You're trying to mix active records with normal CI queries and that won't work. Change the query to:
$query = $this->db->query("SELECT * FROM news WHERE LEFT(slug, 1) = '$letter' LIMIT $start, $limit");
Either that or go the active record route entirely with:
$this->db->limit($limit, $start);
$this->db->where('LEFT(slug,1)',$letter);
$this->db->get('news');
As far as I know there is no way to return all the results you need with a single query, the controller needs total records to figure out the pagination, then it needs to select just the records for one page.
You could however just write the query once and change the parameters a bit.
public function term($limit, $start, $letter) {
if($limit > 0)
{
$this->db->limit($limit, $start);
}
$this->db->where('LEFT(slug,1)',$letter);
$this->db->get('news');
Then in your controller you'd get the count like this:
$config["total_rows"] = $this->terms_by_letter->term(0,0,$letter);