Adding WHERE cause to COUNT query - php

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.

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 \')

DB Raw query error in Laravel

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

Error when I used GROUP_CONCAT on mysql query

my code worked good , but when i add
GROUP_CONCAT(CONCAT("<a href='index.php?id=", awards_user.userid, "'>", awards_user.username, "</a>")) AS userlist
to get users-id with username , show me error
Parse error: syntax error, unexpected T_STRING [in this line]
SELECT awards.name as name, awards.link as link,
GROUP_CONCAT(DISTINCT awards_user.username) AS username,
GROUP_CONCAT(DISTINCT awards_user.userid) AS userid,
GROUP_CONCAT(CONCAT("<a href='index.php?id=", awards_user.userid, "'>", awards_user.username, "</a>")) AS userlist
FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
where awards.forumid = '".$_REQUEST['forumid']."'
GROUP BY awards.awardid, awards.name, awards.link
You should escape double quotes " with backslash \ otherwise php will understand this as the end of the string :
$sql = "SELECT awards.name as name
, awards.link as link
, GROUP_CONCAT(DISTINCT awards_user.username) AS username
, GROUP_CONCAT(DISTINCT awards_user.userid) AS userid
, GROUP_CONCAT(CONCAT(\"<a href='index.php?id=\", awards_user.userid, \"'>\"
, awards_user.username, \"</a>\")) AS userlist
FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
WHERE awards.forumid = '" . $_REQUEST['forumid'] . "'
GROUP BY awards.awardid
, awards.name
, awards.link";
The escaping of quotes is an issue. So why not use heredoc syntax like this.
$formid = $_REQUEST['forumid'];
$query = <<<EOT
SELECT awards.name as name, awards.link as link,
GROUP_CONCAT(DISTINCT awards_user.username) AS username,
GROUP_CONCAT(DISTINCT awards_user.userid) AS userid,
GROUP_CONCAT(CONCAT("<a href='index.php?id=", awards_user.userid, "'>", awards_user.username, "</a>")) AS userlist
FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
where awards.forumid = '$formid'
GROUP BY awards.awardid, awards.name, awards.link
EOT;
The idea is heredoc syntax allows for a full string with string replacement & without having to worry about escaping quotes. Or knowing that you can set variables for "<a href='index.php?id=", '> and </a> like this:
$formid = $_REQUEST['forumid'];
$id_link_1 = "<a href='index.php?id=";
$id_link_2 = "'>";
$id_link_3 = "</a>";
$query = <<<EOT
SELECT awards.name as name, awards.link as link,
GROUP_CONCAT(DISTINCT awards_user.username) AS username,
GROUP_CONCAT(DISTINCT awards_user.userid) AS userid,
GROUP_CONCAT(CONCAT($id_link_1, awards_user.userid, $id_link_2, awards_user.username, $id_link_3)) AS userlist
FROM awards LEFT JOIN awards_user ON (awards_user.awardid = awards.awardid)
where awards.forumid = '$formid'
GROUP BY awards.awardid, awards.name, awards.link
EOT;

Put a PHP variable in a SQL Query

I have the following code:
try
{
$sql = 'SELECT id, type, date, amount, description, category
FROM `transactions`
WHERE type = "income"
AND month(date) = '$monthselect'
ORDER BY `transactions`.`id` DESC
LIMIT 0,50';
$result2 = $pdo->query($sql);
}
Now, I want to give this month(Date) a variable which month I want to select. if I put 1, it will give me January. So i thought, if I define a variable with 1, I can use it to select a month, right?
$monthselect = 1;
It doesnt work. What am I doing wrong?
Use prepared statements:
$stm = $pdo->prepare('SELECT id, type, date, amount, description, category
FROM `transactions`
WHERE type = "income"
AND month(date) = ?
ORDER BY `transactions`.`id` DESC
LIMIT 0,50');
$stm->execute(compact('monthselect'));
$result2 = $stm->fetchAll();
Since you're not adding "1" directly in your query, I'm assuming here that the variable comes from user input.
To concatenate strings in PHP you need to use the . operator.
$sql = 'SELECT id, type, date, amount, description, category
FROM `transactions`
WHERE type = "income"
AND month(date) = ' . $monthselect . '
ORDER BY `transactions`.`id` DESC
LIMIT 0,50';
I'll frequently use double quotes to substitute variables in PHP:
$sql = "SELECT id, type, date, amount, description, category
FROM `transactions`
WHERE type = 'income'
AND month(date) = $monthselect
ORDER BY `transactions`.`id` DESC
LIMIT 0,50";
Note that you need to swap the existing double quotes (inside the string) to single quotes. You can escape them too, but I find this way makes it much more readable.
Your issue is that you are trying to use a variable inside single quotes, inside which php is not translated
I find by using double quote marks around my queries it allows me to not only use variables in them but to also be able to use single quote mark around the values passed to the db
$sql = "SELECT id, type, date, amount, description, category
FROM `transactions`
WHERE type = 'income'
AND month(date) = $monthselect
ORDER BY `transactions`.`id` DESC
LIMIT 0,50";

Comparing a constant with an array(or multiple values.)

I am trying to search zipcodes matchin in area of 25 miles.
lets say I got 10 zip codes from my function that holds true.
now I have my value in a variable like this:
$zip_res = A0A 1B0, A0A 1G0, ...
column name is postal_code.
How can I match all values at once with postal_code?
I can not use loop, I have to do it in one time.
any suggestions are welcome.
Edit
MySQL statement where $zip_res is used
$sql= "SELECT distinct(p.id), p.extra FROM practitioner p INNER JOIN practitioner_category pc ON pc.practitioner_id = p.id AND pc.category_id = ";
$sql .= "'" .$this->category. "' ";
$sql .= "AND p.primary_postal_code in " .$zip_res. " WHERE 1 AND p.status = 1 ";
It looks like you're just looking for the IN keyword:
SELECT * FROM TABLE_NAME WHERE POSTAL_CODE IN ($zip_res);
Just as a note, however, you need to be able to quote all of those items first. So you might do this before using the above query:
$zip_res = "'" . str_replace(',',"','",$zip_res) . "'";
You can try to use
select ... from ... where postal_code ALL($zip_res).
But I'm not sure because of in accordance to manual you should use subqueries.
See http://dev.mysql.com/doc/refman/5.5/en/all-subqueries.html

Categories