I'm having trouble to convert the below SQL query into CodeIgniter query builder:
$row = $db->prepare("SELECT DATE(message_timestamp) Date, COUNT(DISTINCT messageid) totalCount FROM ic_deliveryreceipts GROUP BY DATE(message_timestamp)");
This is the latest I've tried:
$this->db->select(DATE(message_timestamp) as 'Date', COUNT(DISTINCT messageid) as 'totalCount');
$this->db->group_by(DATE(message_timestamp));
$query = $this->db->get($this->ic_receipts);
Any help more than welcome!
Thank you
$row = $this->db
->query("SELECT DATE(message_timestamp) Date,
COUNT(DISTINCT messageid) totalCount
FROM ic_deliveryreceipts
GROUP BY DATE(message_timestamp)")
->row();
$row is a stdClass object with two properties: Date, totalCount
echo $row->Date . " " . $row->totalCount;
I think you need quotes, and also put false on the second (optional) parameter in $this->db->select, as seen in codeigniter docs:
$this->db->select() accepts an optional second parameter. If you set
it to FALSE, CodeIgniter will not try to protect your field or table
names. This is useful if you need a compound select statement where
automatic escaping of fields may break them.
Try writing like this:
$this->db->select("DATE(message_timestamp) as 'Date',
COUNT(DISTINCT messageid) as 'totalCount'"
, FALSE);
$this->db->group_by("DATE(message_timestamp)");
$query = $this->db->get($this->ic_receipts);
This is what I finally come up with:
$this->db->select('DATE(message_timestamp) Date, COUNT(DISTINCT messageid) totalCount');
$this->db->from('ic_deliveryreceipts');
$this->db->group_by('DATE(message_timestamp)');
$query = $this->db->get();
Thank you for your suggestions
Related
I have a query with a few subqueries like so
SELECT ...
FROM (SELECT ...
FROM ...
GROUP BY ...) as speedLimitCalc INNER JOIN
(SELECT ...
FROM date a INNER JOIN HOURLY_TEST b ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN '".$date_s."' AND '".$date_e."')
AND HOUR BETWEEN ".$time_s." AND ".$time_e."
AND(LKNO BETWEEN '".$lkno_s."' and '".$lkno_e."')
AND RDNO= '".$rdno."'
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.")
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE) as origtable ON ...
,(SELECT ...
FROM [Dim_date]
WHERE (FULL_DAY_DT BETWEEN '".$date_s."' AND '".$date_e."')
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.") ) as c
ORDER BY ...
where I am inserting variables in the inner query where clause.
I am trying to parametrize this query using odbc_prepare and odbc_execute, however I am running into issues of binding the variables. At present, when I use the following
$result = odbc_prepare($connection, $query);
odbc_execute($result)or die(odbc_error($connection));
to run this query, everything works fine. However, when I try to bind a variable, such as
AND RDNO= ?
...
odbc_execute($result, array($rdno))or die(odbc_error($connection));
I get the following error message.
PHP Warning: odbc_execute() [/phpmanual/function.odbc-execute.html]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter
My guess is that it's because I'm binding a variable in a subquery, since this procedure works when the Where clause is in the top Select query.
I was wondering whether anyone else has encountered this issue before, and how they solved it? Thanks
Fixed the issue by removing the need for parameters in the subquery by separating the query into multiple queries using temporary tables.
$query = "SELECT ...
INTO ##avgspeedperlink
FROM Date a INNER JOIN HOURLY_TEST ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN ? AND ?)
AND HOUR BETWEEN ? AND ?
AND(LKNO BETWEEN ? and ?)
AND RDNO= ?
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$time_s,$time_e,$lkno_s,$lkno_e,$rdno,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
INTO ##daysinperiod
FROM [RISSxplr].[dbo].[Dim_date]
WHERE (FULL_DAY_DT BETWEEN ? AND ?)
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
FROM ##avgspeedperlink, ##daysinperiod
ORDER BY LKNO, OUTBOUND
drop table ##avgspeedperlink
drop table ##daysinperiod";
Note that I had to use double ## for making the temporary tables (single # means that table is local to the query, ## means that the temporary table becomes global for multiple queries).
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();
I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!
$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];
Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...
You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.
//( ! ) Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
No idea getting this problem. Please guys help me out. Here is my code:
$query = "SELECT t1.employeecode, t1.employeename, t2.v, t2.w, t3.total, t3.totals
FROM invoice t1,salaries t2,table1 t3
WHERE t1.employeecode = salaries.employeecode AND
t1.employeecode = t3.employeecode
ORDER BY t1.employeecode ASC";
$result = mysql_query($query,$con);
if(mysql_num_rows($result)>0){
echo '<table><tr><th>Article title</th> </tr>';
while($row=mysql_fetch_array($result)){
//$postedon = strftime("%A %e %b %Y",strtotime($row['postedon']));
echo '<h1><tr><td>'.$row["deparment"].'</td></tr></h1>';
}
Since you aliased your salaries table to t2 you have to reference it as t2 in your where clause:
$query = "SELECT t1.employeecode, t1.employeename, t2.v, t2.w, t3.total,
t3.totals
FROM invoice t1,salaries t2,table1 t3
WHERE t1.employeecode = t2.employeecode AND
t2.employeecode = t3.employeecode
ORDER BY t1.employeecode ASC";
$result is boolean (false) cause there must be problem with your query. Help yourself by getting error in your query using mysql_error(),
$result = mysql_query($query,$con) or die(mysql_error());
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
So use either PDO or MySQLi (IMO PDO is way to go)
it seems your query is not working and fails returning FALSE bool value. To check the reason you need to check your query after dynamically building at run time
follow below steps
$result = mysql_query($query) or die($query."".mysql_error());
check the error message. seems some wrong column must be included
Try changing your salaries to be t2..
WHERE t1.employeecode = salaries.employeecode AND
like
WHERE t1.employeecode = t2.employeecode AND
I don't know, but what I know when we done give some alias to a table, our dbms would read that alias, not that native table name.
I have a problem, where I can't find help. When I delete the ORDER BY and LIMIT addtions, then this query works fine. But with them it causes an "Call to a member function execute() on a non-object"-Error. Using LEFT or INNER JOIN makes no difference.
$sql = "UPDATE tasks JOIN service
ON tasks_account_id = service_id
SET `tasks_status` = 'prog' ,
tasks_user = '".$user."'
WHERE `tasks_status` = 'free' AND `service_besetzt` = '0'
ORDER BY `tasks_client_date` ASC, `tasks_id` ASC
LIMIT ".$limit."";
$result = $db->prepare( $sql );
$result->execute();
Has someone an idea?
Thanks!
The issue is that you are using multiple-table UPDATE and ORDER BY and LIMIT clauses cannot be used with it; however they work nice with a single-table UPDATE. Please refer para 2 on http://dev.mysql.com/doc/refman/5.0/en/update.html.
$db->prepare($sql) is returning null. :)
Maybe the prepare method cannot handle LIMIT/ORDER BY... which makes sense as you cannot order an UPDATE query.