I'm trying to retrieve a count of all unique values in a field.
Example SQL:
SELECT count(distinct accessid) FROM (`accesslog`) WHERE record = '123'
How can I do this kind of query inside of CodeIgniter?
I know I can use $this->db->query(), and write my own SQL query, but I have other requirements that I want to use $this->db->where() for. If I use ->query() though I have to write the whole query myself.
$record = '123';
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get('accesslog');
then
$query->num_rows();
should go a long way towards it.
try it out with the following code
function fun1()
{
$this->db->select('count(DISTINCT(accessid))');
$this->db->from('accesslog');
$this->db->where('record =','123');
$query=$this->db->get();
return $query->num_rows();
}
You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument.
With the second parameter as false, the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
Simple but usefull way:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;
Related
public function insrt_into_aprlog($id)
{
$query = 'insert into log_indent_apval (select id,indent_req_id,item_id,req_qty,approval_qty,approval_status,prod_categry,prod_type from tra_inent_rq_itm_dt where id ='.$id.')';
$result = $this->db->query($query);
$resultarr = $result->result_array();
}
my controller line:
$this->outpatient_model->insrt_into_aprlog($indent_id);
error : Call to a member function result_array() on a non-object
even i tried using in codeigniter model insert_batch(); still no use.
result_array() is used to generate query result . You are trying to insert data in your table i guess, so you shouldn't use that . Try below code.
public function insrt_into_aprlog($id)
{
$query = 'insert into log_indent_apval (select id,indent_req_id,item_id,req_qty,approval_qty,approval_status,prod_categry,prod_type from tra_inent_rq_itm_dt where id ='.$id.')';
return $this->db->query($query);
}
Please visit this
Reference
Look into your query.
INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT table2.column1, table2.column2, 8, 'some string etc.'
FROM table2
WHERE table2.ID = 7;
$query is being initialized to a string and then is accessed for an object. This is inconsistent for sure.
$query is a string, I guess you should use $result->result_array().
This code is working perfectaly in mysql run command
SELECT employeeCode
FROM employee_details
WHERE employeeCode
IN (
SELECT DISTINCT (employeeCode) FROM quiz_answer_detailsWHERE submitTime
IN (SELECT MIN( submitTime ) FROM quiz_answer_details WHERE quizId
IN (SELECT id FROM quiz_details WHERE uploadtime = '2014-04-03')
AND answer IN (SELECT answer FROM quiz_details WHERE uploadtime = '2014-04-03'))
)
But I want to use this code on my codeigniter, but it is not working.
My codeigniter query code is
$this->db->select('employeeCode');
$this->db->from('employee_details');
$this->db->where_in('employeeCode');
$this->db->select('DISTINCT(employeeCode)');
$this->db->from('quiz_answer_details');
$this->db->where_in('submitTime');
$this->db->select('min(submitTime)');
$this->db->from('quiz_answer_details');
$this->db->where_in('quizId');
$this->db->select('id');
$this->db->from('quiz_details');
$this->db->where('uploadtime',"2014-04-03");
$this->db->where_in('answer');
$this->db->select('answer');
$this->db->from('quiz_details');
$this->db->where('uploadtime',"2014-04-03");
$query=$this->db->get();
print_r($query);
if($query->num_rows>=1)
{
return $query;
}
else
{
return false;
}
What is wrong please help me
The problem lies with this code and subsequent similar uses of where_in
$this->db->where_in('employeeCode');
You have given the where parameter value but not what to match with.
for eg.
$this->db->where_in('employeeCode',$subQuery1);
The documentation of where_in:
$this->db->where_in();
Generates a WHERE field IN ('item', 'item') SQL query joined with AND
if appropriate
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names); // Produces: WHERE username
IN ('Frank', 'Todd', 'James')
You have to create a separate sub query for each invocation of where_in.
You should re write you subquery and use joins instead to get the better performance,without having full information regarding your tables/relationship and desired result i can't provide you the new query but you can use your subquery in active record's where function
$subquery=" SELECT DISTINCT (employeeCode) FROM quiz_answer_detailsWHERE submitTime
IN (SELECT MIN( submitTime ) FROM quiz_answer_details WHERE quizId
IN (SELECT id FROM quiz_details WHERE uploadtime = '2014-04-03')
AND answer IN (SELECT answer FROM quiz_details WHERE uploadtime = '2014-04-03')) ";
$this->db->select('employeeCode');
$this->db->from('employee_details');
$this->db->where('employeeCode IN('.$subquery.')',null,FALSE);
$query=$this->db->get();
You should pass third parameter as FASLE in order to prevent the query to be quoted by bacticks
Or you can use query() fucntion to run your raw queries
$query=$this->db->query(' your full query here');
$query->result();
This works:
$sql = "SELECT id
FROM `users`
WHERE `account_status` = '" . $i . "'";
$query = $this->db->query($sql);
var_dump($query->num_rows());
But this doesn't:
$sql = "SELECT COUNT(*)
FROM `users`
WHERE `account_status` = '" . $i . "'";
$query = $this->db->query($sql);
var_dump($query->num_rows());
How to do a num_rows on a COUNT(*) query? Also is doing it the 2nd way any better performance wise?
Doing a COUNT(*) will only give you a singular row containing the number of rows and not the results themselves.
To access COUNT(*) you would need to do
$result = $query->row_array();
$count = $result['COUNT(*)'];
The second option performs much better since it does not need to return a dataset to PHP but instead just a count and therefore is much more optimized.
In CI it's really simple actually, all you need is
$this->db->where('account_status', $i);
$num_rows = $this->db->count_all_results('users');
var_dump($num_rows); // prints the number of rows in table users with account status $i
$query->num_rows()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ..., then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.
As per CI Docs we can use the following,
$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();
If we want to get total rows in the table without any condition, simple use
echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table
it's my way of solving the above given question
model
$this->db->select('count(id) as ids');
$this->db->where('id', $id);
$this->db->from('your_table_name');
thanks
This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.
If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.
Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.
I'd suggest instead of doing another query with the same parameters just immediately running a SELECT FOUND_ROWS()
$list_data = $this->Estimate_items_model->get_details(array("estimate_id" => $id))->result();
$result = array();
$counter = 0;
$templateProcessor->cloneRow('Title', count($list_data));
foreach($list_data as $row) {
$counter++;
$templateProcessor->setValue('Title#'.$counter, $row->title);
$templateProcessor->setValue('Description#'.$counter, $row->description);
$type = $row->unit_type ? $row->unit_type : "";
$templateProcessor->setValue('Quantity#'.$counter, to_decimal_format($row->quantity) . " " . $type);
$templateProcessor->setValue('Rate#'.$counter, to_currency($row->rate, $row->currency_symbol));
$templateProcessor->setValue('Total#'.$counter, to_currency($row->total, $row->currency_symbol));
}
I need some help solving a problem with mySQL, is it possible to pass an array to a function and then run a match agains the array values?
I have this query
function getMenu($cookieId) {
$this->db->select('*');
$this->db->from('categoryTable');
$this->db->join('userMenuTable', 'categoryTable.categoryId = userMenuTable.categoryId', 'left');
$this->db->where('userMenuTable.cookieId', $cookieId);
$query = $this->db->get();
return $query->result_array();
}
Using the $query array that is returned is possible to query the database and get all the values from a table that do not match the array values?
Use this condition in your query:
$this->db->where_not_in('fieldname', $array_of_values);
You won't be able to directly use the array returned in your example, as it comes from a SELECT * and thus it contains all fields of the table. You have to build an array with ONLY the values of the field you want to filter you next query on.
What columns do you have in that array ?
Theoretically you could do a
select from `new table` where `field` NOT IN (Select `field` from `old_table`)
to do this in just one query, or pass your array the NOT IN condition
I researched over the internet, but could not find anything...
I have a mysql db, and records at a table, and I need to get random record from this table at every page load. how can I do that? Is there any func for that?
Appreciate! thanks
SORTED:
link: http://www.derekallard.com/blog/post/ordering-database-results-by-random-in-codeigniter/
$this->db->select('name');
$query = $this->db->get('table');
$shuffled_query = $query->result_array();
shuffle ($shuffled_query);
foreach ($shuffled_query as $row) {
echo $row['name'] . '<br />';
}
Codeigniter provides the ability to order your results by 'RANDOM' when you run a query. For instance
function get_random_page()
{
$this->db->order_by('id', 'RANDOM');
or
$this->db->order_by('rand()');
$this->db->limit(1);
$query = $this->db->get('pages');
return $query->result_array();
}
I've used this before and found it to work fine.
I don't know about codeigniter, but getting a random dataset is
SELECT * FROM table ORDER BY RAND() LIMIT 1
The relevant part is "ORDER BY RAND()", obviously.
Do you know how many records there are in the table? You could do something like this:
$count=mysql_exec('select count(*)-1 from some_table');
$count=rand(1,$count);
then:
select * from
some_Table
limit $count,1
This code snippet worked well for me.
$this->db->select('name');
$this->db->order_by('rand()');
$this->db->limit(1);
$query = $this->db->get('<table>'); //<table> is the db table name
return $query->result_array();
Getting random record from large table is very expensive.
Don't use ORDER BY RAND().
This is a bad idea, but if you have a small table no problem.
In a huge databases this type of queries very slow.
I use codeigniter with datamapper. This is the code which I use to get a record randomly from table Advertiser:
$ad = new Advertiser();
$ad->limit(3);
$ad->order_by('id', 'RANDOM');
$ad->get();
SELECT product_id, title, description
FROM products
WHERE active = 1
AND stock > 0
ORDER BY RAND()
LIMIT 4
The ORDER BY RAND() clause returns random records! You can limit records also using LIMIT.
Lets think we have table where we deleted some rows. There is maybe ID not continues correctly. For sample id: 1,5,24,28,29,30,31,32,33 (9 rows)
mysql_num_rows returns 9
Another methods will return not existing rows:
$count=9; //because mysql_num_rows()==9
$count=rand(1,$count); // returns 4 for sample, but we havn't row with id=4
But with my method you always get existing rows. You can separate code and use first 2 code anywhere on site.
// Inside of Controller Class
function _getReal($id,$name_of_table)
{
$Q=$this->db->where('id',$id)->get($name_of_table);
if($Q->num_rows()>0){return $Q;}else{return FALSE;}
}
function _getLastRecord($name_of_table)
{
$Q=$this->db->select("id")->order_by('id DESC')->limit("1")->get($name_of_table)->row_array();
return $Q['id'];
}
function getrandom()
{
$name_of_table="news";
$id=rand(1,$this->_getLastRecord($name_of_table));
if($this->_getReal($id,$name_of_table)!==FALSE)
{
echo $id;
// Here goes your code
}
else
{
$this->getrandom();
}
// END
Getting random record from large table is very expensive. But bellow this code is very effective ..
$count=mysql_num_rows(mysql_query("select * from table_name WHERE SOME_OF_YOUR_CONDITION"));
$nums=rand(1,$count);
mysql_query(" select * from table_name WHERE SOME_OF_YOUR_CONDITION LIMIT $count,1");
This will be helpful ...
I think this is not best way. For sample, you've deleted record which is now==$count. You must iterate this for mysql_num_rows()
This function retrieve all rows in table in random order
public function get_questions(){
$this->db->select('*');
$this->db->order_by('rand()');
$this->db->from('multiple_choices');
$query = $this->db->get();
return $query->result_array();
}
Random row without ORDER BY RAND() query:
$all_rows = $this->db->get('table')->result_array();
$random_row = $all_rows[rand(0,count($all_rows)-1)];