Code Igniter Count Function - php

What I want to do is I want to count the total records from the table called "songs_tbl" from my database. So I wrote this function in controller.
private function getHeaderInfo()
{
$total_songs = $songs->count('distinct songs_tbl.song_id');
$this->mysmarty->assign('total_songs',$total_songs);
}
I got this error
Fatal error: Call to a member function count() on a non-object in
Any suggestion ? Thank you.
With Regards,

I think you are looking for:
$this->db->count_all('songs_tbl');
or if you want the distinct in there you will need to do something like this:
$this->db->select('song_id');
$this->db->distinct();
$this->db->from('songs_tbl');
$query = $this->db->get();
return $query->num_rows();
As there is/was? an issue with using count_all_results() function and DISTINCT
EDIT
I have never used smarty but based on the code in the question I imagine something like this might work, please correct me if I am wrong:
private function getHeaderInfo()
{
$total_songs = get_all_songs();// This function should be called through a model
$this->mysmarty->assign('total_songs',$total_songs);
}
function get_all_songs(){ //THIS SHOULD BE IN A MODEL
$this->db->select('song_id');
$this->db->distinct();
$this->db->from('songs_tbl');
$query = $this->db->get();
return $query->num_rows();
}
Edit 2
My suggested layout would be something along these lines (UNTESTED) using CodeIgniter WITHOUT smarty:
Model Song.php
class Song extends CI_Model {
//Constructor and other functions
function count_all_songs(){
$this->db->select('song_id');
$this->db->distinct();
$this->db->from('songs_tbl');
$query = $this->db->get();
return $query->num_rows();
}
}
Controller Songs.php
class Song extends CI_Controller {
//Constructor and other functions
function index(){ //This could be any page
$this->load->model('Song'); //Could be in constructor
$total_songs = $this->Song->count_all_songs();
$this->load->view('songs_index.html', array('total_songs' => $total_songs));
}
}
View songs_index.html
<html><head></head><body>
Total Songs: <?php echo $total_songs ?>
</body></html>

You could query the table and request a count from the table itself, like this:
$result = mysql_query(SELECT count(*) FROM songs_tbl);

Try this
echo $this->db->count_all('songs_tbl');
It permits you to determine the number of rows in a particular table.

you can use this
$query = $this->db->get('distinct');
if($query->num_rows())
{
return $query->num_rows();
}else{
return 0;
}

Related

calculate the same amount of data on mysql using codeigniter

I want to calculate the same amount of data in one field as in this database
Code Model "M_profile"
class M_profile extends CI_Model
{
public function get_count()
{
$sql = "SELECT count(kd_order) as total FROM tbl_order WHERE kd_pelanggan group by kd_order";
$result = $this->db->query($sql);
return $result->row()->total;
}
}
Using the query builder instead of writing the queries yourself is always a good idea.
From what I see of your table your function should look something like this:
class M_profile extends CI_Model
{
public function get_count()
{
$this->db->select('count(kd_order) as total');
$this->db->group_by('kd_order')
$q = $this->db->get('tbl_order');
return $q->row()->total;
}
}
This way you'll get all the items grouped by order.
Your question isn't clear to me. I am little bit confused. If you want to count based on a condition, you should be put where with a value like this:
class M_profile extends CI_Model
{
public function get_count()
{
$query = $this->db->select('COUNT(kd_order) as total')
->where('kd_pelanggan', $your_value)
->group_by('kd_order')
->get('tbl_order');
return $query->row()->total;
}
}
Or if you want to count without any condition then try this:
class M_profile extends CI_Model
{
public function get_count()
{
$query = $this->db->select('COUNT(kd_order) as total')
->group_by('kd_order')
->get('tbl_order');
return $query->row()->total;
}
}

How to call 2 model function in one function controller in codeigniter

I am new to codeigniter, so please help me to solve my problem.
I want to call my two model function in one function controller. Heres my two model function:
public function getposts($postid){
$this->db->select('*');
$this->db->from('tbl_endangered');
$this->db->where(['endangeredid'=>$postid]);
$query = $this->db->get();
return $query->result();
}
public function getSinglePost($postid){
$this->db->select('*');
$this->db->from('tbl_images');
//$this->db->join('tbl_images');
$this->db->where(['endangeredid'=>$postid]);
$query = $this->db->get();
return $query->result();
}
And here is my function controller:
public function viewAnimals($postid){
if(!$this->session->userdata("id") )
return redirect("AuthCon/login");
$this->load->model('Show');
$posts = $this->Show->getSinglePost($postid);
//$posts = $this->Show->getposts($postid);
$this->load->view('Showimage',['posts'=>$posts]);
}
In that code above I always get the first one that I declared. I want to fetch the getposts and getSinglePost inside the function viewAnimals controller.
Hopeyou can help me. Thanks in advance
I think using same variable name is creating a mess.
you can try assigning to posts array with output in it.
$this->load->model('Show');
$posts['getSinglePostData'] = $this->Show->getSinglePost($postid);
$posts['getPostsData'] = $this->Show->getposts($postid);
$this->load->view('Showimage',$posts);
Do like this in the controller
public function viewAnimals($postid){
if(!$this->session->userdata("id"))
return redirect("AuthCon/login");
$this->load->model('Show');
$data['images'] = $this->Show->getSinglePost($postid);
$data['endangered'] = $this->Show->getposts($postid);
$this->load->view('Showimage', $data);
}
Another way is to use join() and only one model function
public function getSinglePost($postid){
$this->db->select('*');
$this->db->from('tbl_images');
$this->db->join('tbl_endangered', 'tbl_endangered.endangeredid = tbl_images.endangeredid');
$this->db->where('tbl_images.endangeredid', $postid);
return $this->db->get()->result();
}

Why I can't retrieve all data given an ID? php-codeigniter

I'm trying to retrieve data from datbase given an ID number.
Controller:
Usuario.php
public function seleccionar_por_id_estado(){
$id_estado = $this->input->post('id_estado');
$result = $this->usuario_m->ver_datos_por_id($id_estado);
$data['result'] = $result;
$this->load->view('paginas/administrar_usuarios', $data);
}
My Model
usuario_m.php
public function ver_datos_por_id($id_estado){
$condicion = "estado =" . "'". $id_estado ."'";
$this->db->select('*');
$this->db->from('usuarios');
$this->db->where($condicion);
$query = $this->db->get();
return $query->result();
}
My View
administrar_usuarios.php
<form action="usuario/seleccionar_por_id_estado">
<div class="content well">
<label>Ver por:
<select id="id_estado">
<option>Activo</option>
<option>Inactivo</option>
</select>
<?php
foreach ($result as $u){?>
<?php echo $u->usuario;?> <br>
<?php } ?>
</form>
The error that I'm getting is that the var $result is not defined.
Could you help me, please? Thanks!
In your model.Set condition inside $this->db->where() like this
<?php
public function ver_datos_por_id($id_estado){
$this->db->select('*');
$this->db->from('usuarios');
$this->db->where('estado',$id_estado);//set your condition here
$query = $this->db->get();
return $query->result();
}
OR use $this->db->get_where
$query = $this->db->get_where('usuarios',array('estado'=>$id_estado));
return $query->result();
For more see docs Codeigniter Query Builder
UPDATE
Controller:
public function seleccionar_por_id_estado(){
$id_estado = $this->input->post('id_estado');
$data['result'] = $this->usuario_m->ver_datos_por_id($id_estado);
$this->load->view('paginas/administrar_usuarios', $data);
}
I think issue is in your where condition in model.
use this query
$query = $this->db->get_where('usuarios', array('column name of your table' => $condicion));
First, I'd check to be certain that $id_estado isn't empty.
Another possible problem is that Codeigniter really wants you to capitalize class and file names. I'd try renaming the model to 'Usuario_m.php', name the class in the model Usuario_m, and then load it by calling $this->load->model('Usuario_m); (looks like you forgot to load the model too) and then finally call the model function like this:
$result = $this->Usuario_m->ver_datos_por_id($id_estado);
Update
Your where() parameters are wrong too. Your entire function in the model can be just this:
public function ver_datos_por_id($id_estado){
return $this->db->get_where('usurarios', array('estado' =>$id_estado)->result();
}
The get_where function combines get() and where(), chooses the table with the first parameter (so you don't need $this->db->from('usuarios');)

Return a single row in model, pass it to controller and view - Codeigniter

Sorry for posting such a noob question, but I've had hard times when working with returning a single
row from database and pass it to model. Here's my method from my model:
public function test($user_id)
{
$query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '.$user_id.'");
return $query->first_row('array');
}
Here's an example of my controller with some other returned value from my model:
class MY_Controller extends CI_Controller
{
public $layout;
public $id;
public $data = array();
public function __construct()
{
parent::__construct();
$this->output->nocache();
$this->load->model('subject_model');
$this->load->model('user_model');
$this->load->model('survey_model');
$this->id = $this->session->userdata('user_id');
$this->data['check_if_already_posted_it_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('it_survey', $this->id);
$this->data['check_if_already_posted_lvis_survey'] = $this->survey_model->checkIfAlreadyPostedSurvey('lvis_survey', $this->id);
$this->data['test']= $this->survey_model->test($this->id);
$this->layout = 'layout/dashboard';
}
I can pass all the values from that data array to my view except "test". I've basically tried everything.
CheckIfAlreadyPostedSurvey method will return
number of rows with num_rows and I can easily print the value from them in my view by writing:
<?=$check_if_already_posted_it_survey?>
What should I do to print out that "test" in my view?
Thanks in advance and apologizes...
I probably got the question wrong, but have you tried
echo $this->survey_model->test($this->id);
Try this:
public function test($user_id)
{
$query = $this->db->query("SELECT COUNT(*) AS test FROM test WHERE user_id = '".$user_id."'");
return $query->row()->test;
}
This will return a single row as an object and then the referenced row name, which in this case is test.
The following will also work.
public function test($user_id)
{
$query = $this->db->query("SELECT * FROM test WHERE user_id = '".$user_id."'");
return count($query->result());
}
You also messed up the quoting in your SQL statement.

Codeigniter : How can call model funcation in View?

i have model and defined 2 function
1.getMember()
2. getMemberCommunity($member_id)
Controller code
public function index($pass=null){
$this->load->model('member_model');
$data['query']=$this->member_model->getMember();
$this->load->view('backend/project',$data);
}
View
foreach($query as $row) {
// i want to call my another model function ?
//please give me any solutions ya tips
}
You could do something like this by joining the members table where the member id is equal to the member id in the member community table, I think this is what you want:
Model
public function getMembers(){
$this->db->from('members')
->join('member_community', 'members.id = member_community.member_id', 'left');
$members = $this->db->get();
return $members;
}
Controller
public function index($pass=null){
$this->load->model('member_model');
$data['query']=$this->member_model->getMembers();
$this->load->view('backend/project',$data);
}
View
foreach($query->result_array() as $row) {
// do whatever in here
}

Categories