DB Raw query error in Laravel - php

This is my sql.. When i run it to phpmyadmin it is run ok. But when i am going to run as DB:raw in laravel5.5 it shows error. Here, Auckland is not column name.
$result = DB::select("select DISTINCT(SELECT count(id) FROM
commercial_lease where LENGTH(CONCAT(region,city,"Auckland")) =
LENGTH(location) ) as listing_without_address ,(SELECT count(id) FROM
commercial_lease where LENGTH(CONCAT(region,city,"Auckland")) <
LENGTH(location)) as listing_with_address ,(SELECT count(id) FROM
commercial_lease WHERE first_agent_name = 'None' and
second_agent_name='None') as private_listing from commercial_lease");

You are mixing quotes. Query is covered by double quotes and for Auckland you are trying to put these in double quotes again which is issuing an error.
To fix this issue you can escape your string like \"Auckland\" or using single quotes 'Auckland'
$result = DB::select("select DISTINCT
(SELECT count(id) FROM commercial_lease where LENGTH(CONCAT(region,city,'Auckland')) = LENGTH(location) ) as listing_without_address ,
(SELECT count(id) FROM commercial_lease where LENGTH(CONCAT(region,city,\"Auckland\")) < LENGTH(location)) as listing_with_address ,
(SELECT count(id) FROM commercial_lease WHERE first_agent_name = 'None' and second_agent_name='None') as private_listing from commercial_lease");

Related

how to execute complex mysql queries in laravel

I have one below mysql query that is working fine but i want to run it laravel using prepare statement.
SET #sql = NULL;
SELECT GROUP_CONCAT(CONCAT("SELECT '",colname,":' AS 'Label',GROUP_CONCAT(JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.", colname,"'))) AS 'val' FROM mytable GROUP BY Label") SEPARATOR " UNION ")
INTO #sql
FROM
(WITH RECURSIVE data AS (
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), '$[0]') AS colname, 0 AS idx FROM mytable
UNION
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), CONCAT('$[', d.idx + 1, ']'))
AS colname, d.idx + 1 AS idx FROM data AS d
WHERE d.idx < JSON_LENGTH(JSON_KEYS(attr_details)) - 1
) SELECT colname
FROM data
GROUP BY colname) V;
PREPARE stmt FROM #sql;
EXECUTE stmt;;
Now i have tried to convert in larvel like below
$PDO=DB::connection('mysql')->getPdo();
$stmt = $PDO->prepare(<<<_OUT
SET #sql = NULL;
SELECT GROUP_CONCAT(CONCAT("SELECT '",colname,"' AS 'Label',GROUP_CONCAT(JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.", colname,"'))) AS 'val' FROM product_attributes GROUP BY Label") SEPARATOR " UNION ")
INTO #sql
FROM
(WITH RECURSIVE data AS (
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), '$[0]') AS colname, 0 AS idx FROM product_attributes
UNION
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), CONCAT('$[', d.idx + 1, ']'))
AS colname, d.idx + 1 AS idx FROM data AS d
WHERE d.idx < JSON_LENGTH(JSON_KEYS(attr_details)) - 1
) SELECT colname
FROM data
GROUP BY colname) V;
_OUT
);
$stmt->execute();
$result = $stmt->fetchAll();
echo "<pre>"; print_r($result); die;
I am getting this error "syntax error, unexpected 'SELECT' (T_STRING), expecting ')'",
Can anyone help me what i am doing wrong
Please check your quotes at first. In the code "SELECT GROUP_CONCAT(CONCAT("SELECT PHP recognizes that as complete string "SELECT GROUP_CONCAT(CONCAT(" and something undefined SELECT ' with the next string, without concatenation.
At least for me my IDE highlights your code as incorrect. To deal with various quotes try to use that approach
$stmt = $PDO->prepare(<<<_OUT
SELECT * FROM `table` WHERE "1";
_OUT
);
Try to write the request without #sql variable, without PREPARE stm and without EXECUTE stm. I think, PDO will deal with preparing and executing by itself.
$stmt = $PDO->prepare(<<<_OUT
SELECT GROUP_CONCAT() ...
FROM data
GROUP BY colname) V;
_OUT
);
$stmt->execute();
$stmt->fetchAll();
Try to use Laravel approach: DB::select(DB::raw($sql));
SELECT GROUP_CONCAT(CONCAT("SELECT
^-- this quote must be escaped like this: \"
PHP thinks that your SQL string ends there.
Check the other quotes as well.
Edit: Other option might be to wrap the whole SQL to single quotes (') and then just escape those inside the query (by \')

ZF2 Remove column quotes in query

Since a while I am trying to remove the quotes of my mysql query in a ZF2 application. I need to remove the quotes to make this query works, testing the query over command line succeeded by removing the quotes around GEODIST().
$adapter = $serviceLocator->get('SphinxSearch\Db\Adapter\Adapter');
$sql = new Sql($adapter);
$select = new Select;
$select ->columns(array('*', 'distance' => 'GEODIST(23.3556740442177, 2.9525189115381, latitude, longitude)'))
->from('table_name')
->where(array('distance > ?' => 250000))
->order('distance ASC')
->limit(25);
echo $select->getSqlString(new SphinxQL());
Outputs
SELECT *, `GEODIST(23.3556740442177, 2.9525189115381, latitude, longitude)` AS `distance` FROM `table_name` ORDER BY `distance` ASC LIMIT 0,25
I've found the follow solution to make this work by resetting the query with a simple replacer.
$statement = $sql->prepareStatementForSqlObject($select);
$statement ->setSql(str_replace('`', '', $statement->getSql()));
This did the job for me.

Error using mySQL build in operators

I am using the MySQL build-in operators to get a running total, the query works well when I run it in phpMyAdmin, but running it in php does not work, I just get the "Couldn't execute query" message.
My database connection works fine, thus can I do this in php or is there another way to get this to work?
Here is the script:
include("../../include/xxx.inc");
$cxn = mysqli_connect($host,$user,$password,$dbname);
$query = "SET #runtot:=0;
SELECT `q1`.`c`, (#runtot := #runtot + `q1`.`c`) AS rt
FROM (
SELECT SUM( `sr`.`sr_qty` * `st`.`st_ton` ) AS c, `sr`.`sr_no`
FROM `sr`
JOIN `st` ON `sr`.`st_code` = `st`.`st_code`
WHERE `sr`.`sr_date` BETWEEN '2015-01-15' AND '2015-02-15'
GROUP BY `sr`.`sr_no`
ORDER BY `sr`.`sr_no`) AS q1";
$result = mysqli_query($cxn,$query)
or die ("Couldn't execute query.");
while($row = mysqli_fetch_assoc($result))
{
extract($row);
echo "$rt Ton";
Try setting the variable inside the query, so you only have one statement:
SELECT `q1`.`c`, (#runtot := #runtot + `q1`.`c`) AS rt
FROM (
SELECT SUM( `sr`.`sr_qty` * `st`.`st_ton` ) AS c, `sr`.`sr_no`
FROM (SELECT #runtst := 0) vars cross join
`sr`
JOIN `st` ON `sr`.`st_code` = `st`.`st_code`
WHERE `sr`.`sr_date` BETWEEN '2015-01-15' AND '2015-02-15'
GROUP BY `sr`.`sr_no`
ORDER BY `sr`.`sr_no`) AS q1
I'm not completely sure, but i think it's all your `'s
i would do SELECT 'q2.c', (# an so on.
But again, i might be wrong, but it's something to try.
You can't run multiple queries with mysqli_query. You need to call it separately for each query:
$query1 = "SET #runtot:=0"
$query2 = "SELECT `q1`.`c`, (#runtot := #runtot + `q1`.`c`) AS rt
FROM (
SELECT SUM( `sr`.`sr_qty` * `st`.`st_ton` ) AS c, `sr`.`sr_no`
FROM `sr`
JOIN `st` ON `sr`.`st_code` = `st`.`st_code`
WHERE `sr`.`sr_date` BETWEEN '2015-01-15' AND '2015-02-15'
GROUP BY `sr`.`sr_no`
ORDER BY `sr`.`sr_no`) AS q1";
mysqli_query($query1);
$result = mysqli_query($query2);
You can also put variable initializations into a subquery:
$query = "SELECT `q1`.`c`, (#runtot := #runtot + `q1`.`c`) AS rt
FROM (
SELECT SUM( `sr`.`sr_qty` * `st`.`st_ton` ) AS c, `sr`.`sr_no`
FROM `sr`
JOIN `st` ON `sr`.`st_code` = `st`.`st_code`
WHERE `sr`.`sr_date` BETWEEN '2015-01-15' AND '2015-02-15'
GROUP BY `sr`.`sr_no`
ORDER BY `sr`.`sr_no`) AS q1
CROSS JOIN (SELECT #runtot := 0) AS init";
mysqli also has mysqli_multi_query, which allows running multiple queries, but I've seen too many people run into problems to recommend it. It's rarely needed, IMHO.

Adding WHERE cause to COUNT query

I am having trouble getting a where clause to be part of a COUNT query.
This works to get total count of the table:
$search = $_POST['search_text'];
SELECT COUNT(*)
FROM
stories')
->fetchColumn();
However, when I try to add WHERE stories.category = $search i get syntax errors when I try any of these:
$total = $dbh->query('
SELECT
COUNT(*)
FROM
stories
WHERE
stories.category = "$search"
');
->fetchColumn();
FROM
stories
WHERE stories.category='$search'
FROM
stories
WHERE (stories.category="$search")
You can use a variable inside double quotes, but must use concatenation to use one inside single quotes. (ex.. 'my string '.$myvar.' some more string' )
SQL expects strings in either format '' or "" so you can use them interchangeably or with escaped quotes ...
You can escape like this inside of single and double quotes ...
" \" <--- puts a quote in without terminating the string "
' \' <--- same with single quotes '
$total = $dbh->query("
SELECT
COUNT(*)
FROM
stories
WHERE
stories.category = \"$search\"
")
->fetchColumn();
Or
$total = $dbh->query("
SELECT
COUNT(*)
FROM
stories
WHERE
stories.category = '$search'
")
->fetchColumn();
OR
$total = $dbh->query("
SELECT
COUNT(*)
FROM
stories
WHERE
stories.category = '".$search."'
")
->fetchColumn();
Or
$total = $dbh->query('
SELECT
COUNT(*)
FROM
stories
WHERE
stories.category = \''.$search.'\'
')
->fetchColumn();
Also, you can't do this...
');
->fetchColumn();
You are terminating with semi colon, then trying to invoke an object method.

MySQL query to select specific data

I would like to display the data that belongs to any of my users when they login to the site, as well as the name of each table (they completed offers on them).
This is the code I used, but when I add it it's not working.
$result = mysql_query('SELECT *,\'tbl1\' AS tablename FROM (SELECT * FROM table1 WHERE user_id='$user_id') as tbl1 UNION SELECT *,\'tbl2\' AS tablename FROM (SELECT * FROM table1 WHERE user_id='$user_id') as tbl2'. ' ORDER BY `date` DESC');
while($sdata = mysql_fetch_array($result)){
echo $sdata['date'];
echo $sdata['tablename'];
echo $sdata['user_reward'];
}
Where did I make a mistake?
You are missing the concatenation operators here, around $user_id:
$result = mysql_query(
'SELECT *,\'tbl1\' AS tablename FROM (
SELECT * FROM table1 WHERE user_id=' . $user_id . '
) as tbl1
UNION
SELECT *,\'tbl2\' AS tablename FROM (
SELECT * FROM table1 WHERE user_id=' . $user_id . '
) as tbl2' . ' ORDER BY `date` DESC'
);
I've wrapped the call for more clarity - I suggest you do the same in your own code. I'd be inclined to use " marks here instead, so you don't need to escape apostrophes.
The ORDER BY clause seems to be redundantly concatenated as well - remove the dot and add this part of the query to the as tbl2 part.
Here's how I would do it:
$sql = "
SELECT *, 'tbl1' AS tablename FROM (
SELECT * FROM table1 WHERE user_id={$user_id}
) as tbl1
UNION
SELECT *, 'tbl2' AS tablename FROM (
SELECT * FROM table1 WHERE user_id={$user_id}
) as tbl2
ORDER BY `date` DESC
";
$result = mysql_query($sql);
Make sure that $user_id is properly escaped or cast, to avoid security problems. Also, this database library is no longer recommended, and will be removed in a future version of PHP. It would be better to move to PDO or mysqli, and use parameterisation.
Finally, it does rather look like the query itself is rather cumbersome - it looks like it could be simplified. Perhaps ask a separate question on that?

Categories