In Zend, I usually use fetchOne to recept my result when I have only one result (string or int) from my query.
For example :
My model (Zend) :
$query = "
SELECT COUNT(*)
FROM user
";
return $this->getAdapter()->fetchOne($query, null, Zend_Db::FETCH_OBJ);
and in my controler (Zend) :
$table = new Application_Model_TUser;
$number = $table->nUser();
echo $number; // return 5
I would like to do the same thing into CodeIgniter... It's possible ? or am i forced to do :
return $this->db->query("SELECT COUNT(*) AS Nb FROM user")->row()->Nb;
You could do:
return $this->db->count_all('user'); // returns int
Or if you want to add conditions use:
$this->db->from('user');
$this->db->where($conditions);
return $this->db->count_all_results(); // returns int
Update: Based on your comment, it would be best to get it like your have written in your question:
return $this->db->query("SELECT COUNT(*) AS Nb FROM user")->row()->Nb;
Or without using query(), in more of an "active record" fashion:
$where = array('userID'=>'1');
$query = $this->db->get_where('user', $where);
$row = $query->row();
return $row->name;
Related
$array = array('classesID' => 6);
$this->db->select()->from($this->_table_name)->where($array)->order_by($this->_order_by);
$query = $this->db->get();
return $query->result();
I need to get the rows where the classesID is 6. Some rows contain 6,5,4.
so i need to use FIND_IN_SET query to retrive where the classesID is 6.
Please guide me
Thanks
I need to get the rows which has student id '4488' and message id '1418'
$id = 1418;
$student_id = 4488;
this->db->select('id, action_status, updated_on, student_ids');
$this->db->where('message_id', $id);
$this->db->where('find_in_set("'.$student_id.'", student_ids) <> 0');
$this->db->from('actions_history');
$query = $this->db->get();
It will return a query like
SELECT id, action_status, updated_on, student_ids FROM actions_history WHERE message_id = '1418' AND find_in_set("4488", student_ids) <>0
Try this
$array = array('classesID' => '5,6,7');
$this->db->select();
$this->db->from($this->_table_name);
$this->db->where("FIND_IN_SET('classesID',".$array['classesID'].")",null,false);
$this->db->order_by($this->_order_by);
$query = $this->db->get();
return $query->result();
You can write the query like this.
return $this->db->where('classesID' , '6')->order_by('column_name','desc')->get('table_name')->result_array();
if Need any help comment
For those who're looking for model (CI v4.x) based solution,
$modal->where("FIND_IN_SET('<string to find>', '<column name>')", null, false)->findAll();
In your case,
$modal->where("FIND_IN_SET('".$array['classesID']."', 'classesID')", null, false)->findAll();
I am currently using below code to sum up numbers of quantity based on a ID
targeting mysql quantity column, just wondering if this is the best practice using codeigniter? or is there a shorter way to execute this.
My Model.php
public function sum_quantity_of_stacks($id){
$query = $this->db->query("SELECT *, SUM(qty) as total FROM stocks WHERE drug_id = '$id'");
return $query->row_array();
}
public function sum_quantity_of_request($id){
$query = $this->db->query("SELECT *,SUM(quantity) as total_request FROM med_request WHERE med_given = '$id' AND status = 'Approved'");
return $query->row_array();
}
Then my view.php
$id = $medicine['ID'];
$data['get_count'] = $this->Medicine_model->sum_quantity_of_stacks($id);
$data['get_request'] = $this->Medicine_model->sum_quantity_of_request($id);
$total_available = $data['get_count']['total'];
$total_given = $data['get_request']['total_request'];
echo $total_available - $total_given;
Above code gives me the current available stocks of my medicine inventory.
No, there are no such way to do that, similar to what are you are doing now.
SELECT other column with SUM feature not possible
But there are a method name select_sum() available in query builder by which you may get SUM only like
public function sum_quantity_of_stacks($id){
$this->db->select_sum('qty','total');
$this->db->where('drug_id',$id);
$query = $this->db->get('stocks');
$res = $query->row_array();
//now SUM is available in $res['total']
return $res['total'];
// or return $query->row_array();
}
I am confuse with this problem in mysql, I have two table, "A" and "B"
TableA:
S.No contact1 contact2 status
1 Blbh eeee 1
TAbleB:
S.No Phone1 phone2
1 ddd ssss
From this table i am going to get value, from TableA ia m going to check
if (status == 1)
{
run tableA;
}
else
{
run table b;
}
I am gone a return result of this query. In view, how to get value with respected column name. I have no idea of this, help me to get value in view.
public function contDetails($id){
$check = $this->db->query("SELECT contact_status FROM account WHERE id = '$id' ");
$str = $check->row();
$chk = $str->contact_status;
if($chk == 1){
$query = $this->db->query("SELECT * FROM account WHERE id = '$id'");
}else{
$query = $this->db->query("SELECT * FROM contact_details WHERE user_id = '$id'");
}
$run = $query->num_rows();
print_r($run);
}
You can use in your model
$query = $this->db->get(); //--- run the query ---//
return $query->result() //--- to get result in array of object ---//
and then in your view use foreach loop
foreach($results as $result){
echo $result->columnName;
}
have you already written the query in mysql? If yes and if you are concerned about whether the column name to use exist or not you can use isset...
in your view you can use like the following:
<?php
foreach($results as $result)
{
echo (isset($result['col1']))?$result['col1']:$result['col1_2'];
}
?>
And don't forget to use result_array() instsead of result in the controller
I know this is simple php,however I am having great trouble getting my logic written out with codeigniter.
I am trying to pull the 12 most recent users and display their info in a view. I have made a 'created_on' field in my database table to track activity of signing up.
When I specify an id in my controller I am able to pull results that I'm passing from my model to my controller and then my view, however it's only pulling one user like so.
MODEL:
public function newest_members()
{
$session = $this->session->userdata('is_logged_in');
$user_id = $this->session->userdata('id');
$query = $this->db->query("SELECT * FROM users WHERE status = 'active' && id = $user_id ORDER BY created_on DESC LIMIT 12");
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data;
}else{
return array();
}
}
CONTROLLER:
public function dashboard()
{
$this->load->library('session');
$this->load->helper('date');
$session_id = $this->session->userdata('id');
$this->load->model('account_model');
$this->load->model('community_model');
$user = $this->account_model->user();
$data['user'] = $user;
$newest_members = $this->community_model->newest_members();
$data['newest_members'] = $newest_members;
$data['main_content'] = 'account/dashboard';
$this->load->view('includes/templates/main_page_template', $data);
}
VIEW:
<?php
foreach($newest_members as $nm)
{
echo $nm['first_name']; echo "<br />"; echo $nm['last_name'];
}
?>
That is pulling the result of the NEWEST member and the one that is signed in. However I want to pull ALL signed in or not so I was trying something like this with my model:
public function newest_members()
{
$query = $this->db->query("SELECT * FROM users WHERE status = 'active' ORDER BY created_on DESC LIMIT 12");
// OR YOU CAN USE THE BELOW
// $query = $this->db->query("SELECT * FROM users ORDER BY `created_on` DESC LIMIT 12");
// YOU ALSO MIGHT WHAT TO ADD WHERE `status` = 'active' (or whatever applies for your db table)
// EITHER SPIT OUT RESULTS OR EMPTY ARRAY
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data;
}else{
return array();
}
thanks in advance.
SELECT TOP 12 FROM users WHERE status = 'active' ORDER BY created_on DESC
I'M using mssql for this,, try it if it help
The codeigniter num_rows() function does not return a boolean value but rather the number of results fetched from the database. There fore your model should insead have :
if($query->num_rows() > 0)
{
...
}
see here for more information
You want to pull the 12 newest active members? You had it right.
SELECT * FROM users WHERE status = 'active' ORDER BY created_on DESC LIMIT 12
Also, you don't want to check if just one row is returning. You want to check if more than zero rows are returning. You need to do this instead:
if($query->num_rows() > 0)
{
$data = $query->result_array();
return $data;
}
Since your using codeigniter it has a wonderful feature called active record that makes working with a database much easier and more secure then writing raw queries as strings which could result in SQL injection. Here is your function below both utilizing active record and returning the results your expecting.
public function newest_members()
{
//Select the 12 newest users
$result = $this->db->where('status', 'active')->order_by('created_on', 'desc')->limit(12)->get('users');
//If results are found return an array otherwise return an empty array
return ($result->num_rows() > 0) ? $result->result_array() : array();
}
Am try to looping through a database result set, the problem is that i know i have only one row of data, yet the loop returns 5 rows
This is my method from my model
function get_latest_pheeds() {
$data = $this->user_keywords($this->ion_auth->user_id);
$keyword = $data;
$user_id = $this->ion_auth->user_id;
foreach($keyword as $key => $word) {
$q = "SELECT *,COUNT(pheed_comments.comment_id) as comments
FROM pheeds
LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id
WHERE pheed LIKE '%$word%' OR user_id='$user_id'
GROUP BY pheeds.pheed_id
ORDER BY datetime DESC";
$result = $this->db->query($q);
$rows[] = $result->result();
}
return $rows;
}
What am i doing wroing
This is because your query has an OR where it should probably have an AND - each query always matches the user_id='$user_id'.
This loop is quite inefficient anyway, I think you want to do something more like this:
function get_latest_pheeds() {
$keywords = $this->user_keywords($this->ion_auth->user_id);
$q = "SELECT *,COUNT(pheed_comments.comment_id) as comments
FROM pheeds
LEFT JOIN pheed_comments ON pheed_comments.P_id=pheeds.pheed_id
WHERE (pheed LIKE '%".implode("%' OR pheed LIKE '%",$keywords)."%') AND user_id='".$this->ion_auth->user_id."'
GROUP BY pheeds.pheed_id
ORDER BY datetime DESC";
return $this->db->query($q);
}
If you want your results returned as an array like they were previously, you'll need to loop over results and fetch each of them into an array key of another array. I can't do it here because I can't see your db class...
EDIT: Slight fix in the above code...
ANOTHER EDIT: another fix...