What I want to do is use sum if in codeigniter, it's got error when I run in browser, but I query in MYSQL, there are not error and working nicely.
Here is my code
$this->db->select('sum(if(`monitoring_type` = 1,1,0)) AS independent,sum(if(`monitoring_type` = 2,1,0)) AS buddy,count(*) AS TM, rate_info.qm_title');
$this->db->from('qm.recordings');
$this->db->join('qm.rate_info', 'recordings.record_id = rate_info.record_id');
$query = $this->db->get();
return $query->result();
my Error
MYSQL
Add FALSE as the second parameter to
$this->db->select('your Query', FALSE);
Update:
It removes the escape identifiers (the backticks) from the select statement which codeigniter does by default for each query. So
SELECT `column1`, `column2` FROM table
will become
SELECT column1, column2 FROM table
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).
acutally i want get search with multi field so i decided to union query and i write my code following
$this->db->select("id, title, job_type");
$this->db->distinct();
$this->db->from("jobs");
$this->db->like('title',$keyword);
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select("company");
$this->db->distinct();
$this->db->from("employers");
$this->db->join('jobs', 'jobs.userId = employers.userId');
$this->db->or_like('company',$company_name);
$this->db->get();
$query2 = $this->db->last_query();
$query = $this->db->query($query1." UNION ".$query2);
return $query->result();
as above code produce following sql query semes like bellow
SELECT DISTINCT `id`, `title`, `job_type` FROM (`jobs`) WHERE `title`
LIKE '%dfsdf%' UNION SELECT DISTINCT `company` FROM (`employers`) JOIN
`jobs` ON `jobs`.`userId` = `employers`.`userId` WHERE `company` LIKE '%%'
and it shows following error
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN jobs ON jobs.userId = employers.userId WHERE
company LIKE '%%' at line 5
can anyone help me
First of all, in order to use union the no. of columns and their data types should match in both the queries.
You are trying to do a union between a query which selects three columns with another query which only one column. This will not work.
To know more about mysql unions, you can go through the below link
http://dev.mysql.com/doc/refman/5.0/en/union.html
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();
The solution to this problem might be a simple over sight of mine.
I am trying to run a MYSQL query stored as a string in PHP. The query runs fine using DBM tool like Navicat but returns false in my PHP development enviorment. Is there something I've over looked?
SET #running_sum = 0;
SELECT
TID,
SumTotal,
T.`Freight`,
T.`Insurance`,
T.`Discount`,
CONCAT(
'$',
FORMAT(
#running_sum :=#running_sum + SumTotal + T.`Freight` + T.`Insurance` - T.`Discount`,
2
)
) AS 'Running Total'
FROM
(
SELECT
TID,
SUM(Quantity * UnitNetValue) AS SumTotal,
T.`Freight`,
T.`Insurance`,
T.`Discount`
FROM
Transactions T
JOIN `Transactions_Products` P ON T.TransactionID = P.TID
WHERE
(
T.TemplateName = ''
OR T.TemplateName IS NULL
)
AND T. STATUS = 1
GROUP BY
TransactionID
) AS T;
I am executing the query like this;
$result = mysql_query($this->query);
$this->query is a string which holds the above query, as it is displayed to you above.
The problem is mysql_query() doesn't support multiple queries. Your SET #running_sum = 0; is considered a separate query and so you'll have to execute that first:
$result1 = mysql_query("SET #running_sum = 0;");
$result2 = mysql_query($this->query); // <-- without the SET ... query
From the Manual:
mysql_query() sends a unique query (multiple queries are not supported)
Side note: The mysql_* library is deprecated, it is recommended to upgrade to a modern MySQL library such as PDO or MySQLi.
There is also possible to use multi_query method instead of query of MySQLi:
$query = "SET #running_sum = 0; SELECT ...";
$db_link->multi_query($query);
put variable like this. i guess it should work.
mysql_query("SELECT #i:=0");
mysql_query("UPDATE table_name SET id = #i:=#i+1");
I have a query:
$result = mysql_query("CREATE VIEW temporary(IngList) AS (
SELECT DISTINCT (r1.Ingredient)
FROM recipes r1,
recipes r2
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'
AND r1.Ingredient = r2.Ingredient)
SELECT COUNT(*) FROM temporary");
I want the query to make a view called temporary and have it return a count of the number of rows in the view temporary. I know this code works without the SELECT COUNT(*) because I checked my database and the view is created.
Yet this code throws the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM temporary' at line 1
I checked the syntax and it seems to be correct. What seems to be the problem because its quite frustrating.
From the mysql_query documentation:
mysql_query() sends a unique query (multiple queries are not supported)...
You can't create the view, and select from it in a single mysql_query. The view is unnecessary:
$sql = sprintf("SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
WHERE r.country = '%s'
AND EXISTS(SELECT NULL
FROM recipes r2
WHERE r2.Country = '%s'
AND r1.Ingredient = r2.Ingredient)",
$temp, $temp2);
$result = mysql_query($sql);
For starters you have two statements. What you're writing looks more like a stored procedure. Even if it worked, you would need a semicolon at the end of the first statement. And another statement somewhere saying "DROP VIEW ...." when you are done.
And a temp view is a bit of a non sequitur. I can't find any reference to "CREATE VIEW temporary". Or maybe it's to create a view named temporary with an argument? Views don't take arguments.
I think you might get what you want with a semi-simple SQL statement something like:
$result = mysql_query(
"SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
JOIN recipes r2 ON r1.Ingredient = r2.Ingredient
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'");