mysql query error in PHP but working in phpmyadmin - php

I have write a query in mysql and it is running in phpmyadmin, but in PHP it giving me 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 docno, docdate, doctype, narration, drcr, (case when drcr = 'Dr' then amo' at line 2
My Query is in PHP is :
$sql = "set #runtot := 0; select docno, docdate, doctype, narration, drcr, (case when drcr = 'Dr'
then amount else 0 end) as debit, (case when drcr = 'Cr' then amount else 0 end) as
credit, concat(abs((#runtot := #runtot + (case when drcr = 'Dr' then amount else amount*-1
end))), (case when #runtot < 0 then ' Cr' else ' Dr' end) ) as balance from (select docno,
docdate, doctype, narration, amount, drcr from ledger where accode = 1 )as q1";
what is wrong here with php?

You have to use transactions to perform several commands in MySQL.
You create a varible first and then execute another command.
Using just single function mysqli_query you can perform only one command and commands are separated by ;.
When you paste the code into PHPMyAdmin, it will work though as it is still supposed to be a transaction.
You can read more about transactions.

Related

SQL Variable inside PHP Statement

My code:
$sql = "SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '".$data[2]."' OR o = '".$data[4]."' ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
$result = mysql_query($sql) or die(mysql_error());
The error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'SELECT (#row_number:=#row_number + 1) AS num, player,
reinforcees, reinforcers F' at line 1
When I echo the SQL statement, I get the following: SET #row_number = 0; SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '1' OR o = '5' ORDER BY CASE WHEN player = '2' THEN 1 ELSE 2 END
When I run that echod statement through phpMyAdmin, it runs successfully, and gives me rows of results.
But why doesn't it work in a PHP statement? What's going on? How do I get PHP to do what SQL is doing?
And before anyone says I haven't tried to find the answer myself, if you Google "sql variable" php site:stackoverflow.com, every question I find is about accessing SQL results in PHP (i.e., loops) or inserting PHP variables in SQL, which is not what I need. I'm trying to insert an SQL variable into the SQL statement.
Also: I realize I should stop using MySQL, and am in the process of converting, but in order to quickly resolve a bug...I'm using MySQL.
mysql_query doesn't support multiple queries in one call. You would need to upgrade to mysqli or PDO to enable that. In the meantime though, you can implement what you want in a single query using a CROSS JOIN to initialise the row_number variable e.g.
$sql = "SELECT (#row_number:=#row_number + 1) AS num, player, reinforcees, reinforcers
FROM _KoT_villages
CROSS JOIN (SELECT #row_number := 0) r
WHERE o = '".$data[2]."' OR o = '".$data[4]."'
ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
The MySQL client in php expects individual statements
Open MySQL client
First Statement:
SET #row_number = 0
2nd Statement:
SELECT
(#row_number:=#row_number + 1) AS num,
player,
reinforcees,
reinforcers
FROM
_KoT_villages
WHERE
o = '".$data[2]."'
OR o = '".$data[4]."'
ORDER BY
CASE WHEN player = '".$user_class->id."' THEN 1
ELSE 2
END
$result = mysql_query( [2nd Statement] ) or die(mysql_error());
Close MySQL client

WHERE NOT IN AND WHERE error

I tried moving the WHERE clause many times but I'm still having an error. Am I doing the WHERE NOT IN AND WHERE clause wrong? The code is working perfectly fine until I added the WHERE ha_rooms.deleted != 1 clause. I also tried using deleted <> 1 but it still shows the same error
$query2 = $this->db->query("SELECT * FROM ha_rooms
WHERE ha_rooms.deleted != 1 JOIN ha_user_room_merged
WHERE ha_rooms.room_id NOT IN (SELECT ha_user_room_merged.room_id
FROM ha_user_room_merged WHERE ha_user_room_merged.deleted = 0)
group by ha_rooms.room_id");
The error is this
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 ha_user_room_merged WHERE ha_rooms.room_id NOT IN (SELECT
ha_user_room_merg' at line 1
If I said frankly, your query is not done properly in anyway but it gives pretty much clear vision of what you are trying to do if you don't have any other logic behind that. So, I would like to suggest you to do google for SQL Syntax, Ordering, use of GROUP BY, WHERE sub-query etc. BTW below is the proper version of your query please check if it's useful for you
SELECT hr.*
FROM ha_rooms hr
JOIN ha_user_room_merged hurm On hurm.room_id = hr.room_id
WHERE hurm.deleted = 0
AND hr.deleted <> 1
Use below codeigniter query. in your join there is no ON
$all_ids = 0;
$this->db->select('group_concat(room_id) as ids');
$this->db->where('deleted', 0);
$ids = $this->db->get('ha_user_room_merged')->row_array();
if($ids) {
$all_ids = explode(',', $ids['ids']);
}
$this->db->where('hr.deleted !=', 1);
$this->db->where_not_in('hr.room_id', $all_ids);
$this->db->join('ha_user_room_merged hrm', 'hrm.room_id = hr.room_id');
$this->db->group_by('hr.room_id');
$this->db->get('ha_rooms hr')->result_array();
Please try..
select * from ha_rooms as a inner join ha_user_room_merged b on a.ha_rooms.id = b.room_id
where b.deleted <> 0
Output
ha_rooms.room_id ha_user_room_merged.room_id deleted
1 1 1
2 2 1
3 3 1
4 4 1
Thanks :)

SQL query with CASE in SELECT doesn't work

I have this part of a larger complex query:
SELECT SUM(pir.priceChange) AS CASE
WHEN (SUM(pir.priceChange) > 0) THEN sellSum
WHEN (SUM(pir.priceChange) < 0) THEN priceSum
END
Whenever I try to pass it on to MySQL (MyISAM) via PDO, it throws me an exception:
Syntax error or access violation: 1064 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 SUM(pir.priceChange) AS CASE WHEN (SUM(pir.priceChange) > 0) THEN sellSu' at line 17
I imagine it has something to do with the fact that I'm trying to use a CASE statement incorrectly. Would really like to know what's exactly wrong, thanks in advance.
EDIT: My full query (edited without any cases):
SELECT pi.id AS id,
pi.type AS type,
pi.parValue AS rating,
pi.duration AS time,
countAmt.amt AS amtSold,
IFNULL(pii.pChange,
0) AS priceTotal,
0) AS costTotal,
IFNULL(pii.selfPrice,
0) AS costPrice,
(IFNULL(pii.sellSum,
0) - IFNULL(pii.selfPrice,
0)) AS profit,
countClose.amtClosed AS amtClosed
FROM salon.paymentInstrument as pi
(SELECT SUM(pir.priceChange) AS pChange,
SUM(pir.costChange) AS cChange,
(IFNULL(pir.priceChange,
0) - IFNULL(pir.costChange,
0)) AS selfPrice,
pii.paymentInstrumentID
FROM salon.paymentInstrumentRegister as pir
JOIN salon.paymentInstrumentItem as pii ON pir.paymentInstrumentItemID = pii.id
WHERE pir.date >= '2014-04-11'
AND pir.date <= '2014-04-25'
GROUP BY pii.paymentInstrumentID
) as pii
(SELECT pii.paymentInstrumentID,
COUNT(*) AS amtClosed
FROM salon.paymentInstrumentItem as pii
WHERE pii.annulTime >= 2014-04-11
AND pii.annulTime <= 2014-04-25
AND pii.status <> "active"
GROUP BY pii.paymentInstrumentID
) as countClose
(SELECT pii.paymentInstrumentID,
COUNT(*) AS amt
FROM salon.paymentInstrumentItem as pii
WHERE pii.startTime >= 2014-04-11
AND pii.startTime <= 2014-04-25
GROUP BY pii.paymentInstrumentID
) as countAmt
Sorry for improper formatting, it's generated dynamically with PHP. I have a feeling i'm making a mistake somewhere else in the query.
Try this way:
SELECT CASE WHEN SUM(pir.priceChange)>0 THEN SUM(pir.priceChange) END as SumPrice,
CASE WHEN SUM(pir.priceChange)<0 THEN SUM(pir.priceChange) END as priceSum
FROM TableName
An example in SQL Fiddle.
Try this:
SELECT CASE
WHEN (SUM(pir.priceChange) > 0) THEN sellSum
WHEN (SUM(pir.priceChange) < 0) THEN priceSum
END

MySQL query can't handle variables

I'm trying to query to my database, but for some reason the query is only working when I enter the parameters hard coded. If I use variables, the query refuses to work...
This is my query with hard coded parameters and works just fine:
$q_jobs = 'select distinct nid from node n, field_data_field_job_tags as tags
where (type= \'job\' and n.language = \'nl\' and tags.entity_id = n.nid
and tags.field_job_tags_value = \'Enterprise Asset Management\')
order by n.changed desc limit 7';
But when I use variables, the query refuses to work...
$q_jobs = 'select distinct nid from node n, field_data_field_job_tags as tags
where (type= \'job\' and n.language = :lang and tags.entity_id = n.nid
and tags.field_job_tags_value = :title)
order by n.changed desc limit 7';
$results_jobs = db_query($q_jobs, array(':lang' => $language->language,
':title' => $node->title));
Although it's a Drupal query, I assume it's just an error somewhere in my syntax?
I get this error:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '(type= 'job' and n.language = 'nl' and tags.entity_id =
n.nid and tags.field_job' at line 1: select distinct nid from {node} n,
field_data_field_job_tags as tagswhere (type= 'job' and n.language = :lang and
tags.entity_id = n.nid and tags.field_job_tags_value = :title)order by
n.changed desc limit 7; Array ( [:lang] => nl [:title] => Enterprise
Asset Management ) in rd_get_related_news_and_blogs()
You have a typo here: field_data_field_job_tags as tagswhere (type= - there should be a space between tags and where so the quoted part of Your SQL should be field_data_field_job_tags as tags where (type=.
Always read all of the mysql error message - the query it is failing with is always quoted thus You can easily find any typo or other mistake in Your query.
EDIT: cos You don't believe me, here is repeated query from the mysql error message:
select distinct nid from {node} n, field_data_field_job_tags as tagswhere (type= 'job' and n.language = :lang and tags.entity_id = n.nid and tags.field_job_tags_value = :title)order by n.changed desc limit 7;
Now see where You have a newline in Your query and where should be (and is not) a space within the query MySQL returned as failing.
Then put a space at the end of every line and see that the query is working...
I will help You, there should be space between tags and where and between \'Enterprise Asset Management\') and order by - but it is NOT. The only space is between n.nid and and tags.field_job_tags_value because of the tab space...

Setting an error limit while updating table based conditions php

I have got a question. I have not done this before and am not sure if that is how it should be done.
I have a mySQL query which is working correctly. I use it in phpMyAdmin query editor whenever I want to do an update. However, I want to make life easier for a user by putting the query in a php script so the user can just click a link and the task is done.
I did the following:
$sql = " SET #error_limit = 10E-6;
UPDATE (
SELECT r.rmc_id, 'rmc_raw_data' src, r.rmc_time, r.rmc_date, r.latitude, r.longitude,
IF(s.server_id IS NULL, 'Mobile', 'Both') c FROM rmc_raw_data r
LEFT JOIN server_log_data s
ON r.rmc_time = s.server_rmc_time AND r.rmc_date = s.server_rmc_date AND ABS(r.latitude - s.server_latitude)/r.latitude < #error_limit AND ABS(r.longitude - s.server_longitude)/r.longitude < #error_limit
UNION
SELECT s.server_id, 'server_log_data' src, s.server_rmc_time, s.server_rmc_date, s.server_latitude, s.server_longitude, IF(r.rmc_id IS NULL, 'Server', 'Both') c FROM rmc_raw_data r
RIGHT JOIN server_log_data s
ON r.rmc_time = s.server_rmc_time AND r.rmc_date = s.server_rmc_date AND ABS(r.latitude - s.server_latitude)/r.latitude < #error_limit AND ABS(r.longitude - s.server_longitude)/r.longitude < #error_limit
) t
LEFT JOIN rmc_raw_data r1
ON r1.rmc_id = t.rmc_id AND t.src = 'rmc_raw_data'
LEFT JOIN server_log_data s1
ON s1.server_id = t.rmc_id AND t.src = 'server_log_data'
SET
r1.data_source = c, s1.data_source = c;";
$result = mysql_query($sql, $link);
if($result){
echo " Query executed successfully";
...
...
So I put the whole thing my php script but got a mysql 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 'UPDATE ( SELECT r.rmc_id, 'rmc_raw_data' src, r.rmc_time, r.rmc_date, r.latit' at line 1
Could someone suggest what am doing wrong here? It is my thinking that the error limit I have set on the first line of the query is responsible but I had thought that one could put his working query in the mysql_query() and it works.
'rmc_raw_data' src, this quotes will break the query ???

Categories