codeigniter query prbolem - php

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();

Related

how to pass variable value to sql query in codeigniter?

is it possible to pass the variable value in mysql query in codeigniter ?
I want to select records from database that have id same as my session id.
my code is :
$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('products');
$this->db->where('id_admin = (SELECT id_admin FROM users WHERE id='.$this->session->userdata('user_id').')', NULL, TRUE);
can we concatenate variable values in database queries?
This code not given any error, but not give any result also.
Use join in active records
$this->db->select('p.*');
$this->db->from('products as p');
$this->db->join('users','p.id_admin=users.id');
$this->db->where('users.id',$this->session->userdata('user_id'),false);
$query = $this->db->get();
An Example Reference of how to write the JOIN Query in CI as per the Documentation of the Active Records.
$article_id = $this->input->post('article_id');
$this->db->select('*');
$this->db->from('articles');
$this->db->join('news', 'news.id = articles.id');
$this->db->where('articles.id',$article_id);
$query = $this->db->get();
The above code will produce the query as follows for execution.
SELECT * FROM articles JOIN news ON news.id = articles.id WHERE articles.id='10'
Provided the passed id is 10
In order to view the Result of the executed query you must perform the below code.
print_r($query->result());
Try like this..use joining of two tables.
<?php
$this->db->select('products.*');
$this->db->from('products');
$this->db->join('users','products.id_admin=users.id_admin');
$this->db->where('users.id',$this->session->userdata('user_id'));
$query = $this->db->get();
print_r($query->result_array());//your array of records

Result from two tables order by date

can you help I have two tables images and note. I would like to get all items from these tables and order by date. It is possible I am using active record in codeigniter. Tables are independent.
Thank you for replies.
this should work:
$this->db->orderby("date", "ASC"); //or desc
$query = $this->db->get('images'); //or $query = $this->db->get('note');
$result=$query->result_array();
print_r($result);
or if you want use union all
$this->db->query('SELECT * FROM (SELECT id, date FROM images UNION ALL SELECT id, date FROM note) result ORDER BY result.date');
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order from http://www.w3schools.com/sql/sql_union.asp.
I think you want a Cross Join.
Here is your codeigniter code
$this->db->from("images ,note");
$this->db->select("images.*,note.*);
//make sure both dont have same column name other wise use this
//$this->db->select("images.column1,images.column2,note.column1);
$this->db->orderby("images.date", "DESC");
//you can add more orderby
//you can add where condition too
$result=$this->db->get()->result_array();
Now you will get the cross product.
Hope it will help you.
In which table do you have date column? I assume you have it in images table.
$this->db->select('images.coulmn1, images.culmn2, images.date_col, note.col1, note.col2');
$this->db->from('images');
$this->db->join('note', 'note.key1 = images.key1); //key1 is key field to relate both table.
$this->db->order_by("images.date_col", "desc");
$result = $this->db->get()->result_array();
Hope it will help.
Try this:
$this->db->select('*');
$this->db->from('images');
$this->db->join('note');
$this->db->orderby("date column name", "ASC");
$query = $this->db->get();
$result=$query->result_array();
print_r($result);

codeigniter select distinct function not working

I have a table with this structure:
opinion_id, author_id, title, content
I would like to get all the latest records from the table, one record for author, that means the latest record for every author...
My distinct function does not seem to be working...
function getOpinions() {
$data = array();
$this->db->select('*');
$this->db->from('opinions');
$this->db->join('authors', 'opinions.author_id = authors.author_id');
$this->db->order_by('date', 'desc');
$this->db->distinct('author_id');
$Q = $this->db->get();
if ($Q->num_rows() > 0) {
foreach($Q->result_array() as $row) {
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
In Codeigniter, distinct does not work the way you expect it by field name. If you look at the manual - there is no argument for distinct. If you look at the code, it only takes a boolean, which defaults to true. It just adds the DISTINCT keyword to the query after the SELECT keyword. That's it.
In your case, I think it would be better to use a GROUP BY as in
$this->db->group_by('opinions.author_id');
Hopefully the order by would work as per your need in this instance by ordering before the grouping.
Cheers!
EDIT - update after OP comments
I know the ordering can be messed up - I sort of mentioned it :)
Anyway, I might be assuming some of your table structure here, but this would force the GROUP BY to pick the rows on the top. I assume that the date is on the opinions table and you only want the latest row from that with author details.
SELECT * FROM `authors`
JOIN (
SELECT * FROM opinions
ORDER BY `date` DESC
) AS ops ON ops.author_id = authors.author_id
GROUP BY ops.author_id
You will not be able to construct this query on active record though. Hope this helps.

How to get max(id) of row data MySql

I want to get the maximum id of row data. In my table first column is id then firstname and etc.
this is the sql command I used to get the max(id) of row data.
<?PHP $maxid=$this->db->query("SELECT MAX(id) FROM `emplyee_personal_details`");
print_r( $maxid) ;?>
but it prints bunch of data as it is a array. But I need only the maximam id of row data for validation before data inserting and updating.
How to get the maxid. I use codeigniter framework.
Try this:
$maxid = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row()->maxid;
UPDATE
This will work even if your table is empty (unlike my example above):
$maxid = 0;
$row = $this->db->query('SELECT MAX(id) AS `maxid` FROM `emplyee_personal_details`')->row();
if ($row) {
$maxid = $row->maxid;
}
The problem with using a raw query like "SELECT MAX(id) ..." is it is not abstract and may not work for every SQL engine. I think the active record way to do it is like this:
$this->db->select_max('id');
$query = $this->db->get('emplyee_personal_details');
// Produces: SELECT MAX(id) as age FROM emplyee_personal_details
See: http://ellislab.com/codeigniter/user-guide/database/active_record.html
SELECT id FROM table ORDER BY id DESC LIMIT 1
That will get you the highest id value, and when I read this, "it prints bunch of data as it is a array" I get the sense that what you really want is a part of that array. DB queries always return complex structures like arrays or objects. So if you wanted just the scalar value (the number as an integer) you might use something like this:
$maxid = (int)$maxid['id'];
or like this (if you have an object):
$maxid = (int)$maxid->id;
HTH, ~Ray
Try this,hope it helps,
return $this->db->select_max('id')
->get('your_table_name')
->row()->id;
public function getMaxCategoryId() {
$query = $this->db->query("SELECT category_id+1 AS maxid FROM " . DB_PREFIX . "category ORDER BY category_id DESC LIMIT 1");
return $query->row['maxid'];
}
error undefined index maxid
<?php`$qry = "select max(ID)+1 As ID from records";`
$result = $con->query($qry);
$row = $result->fetch_assoc();`echo "New ID To Enter = ".$row["ID"];?>
After Connection Just Write This Code It Will Work

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

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;

Categories