PDO MYSQL nested COUNT breaks my query - php

I have query like this:
$query = $con->prepare("SELECT `Id`,
(SELECT count(`Id`)
FROM `images`
WHERE `parentId` = :recId) as `numImgs`
FROM `records`
WHERE `id`= :recId LIMIT 1");
$query->execute(array('recId' => $recId));
$rec = $query->fetch(PDO::FETCH_ASSOC);
When I do this without the nested (SELECT Count(Id)) the query works.
If I take out the SELECT(COUNT(Id)) and do it on it's own, it also works.
For some reason the above query doesn't work. I don't get any errors, just no results. However if I run the query inside phpMyAdmin, it works without any problem and returns two columns, Id and numImgs, eg:
----------------
| id | numImgs |
----------------
| 50 | 10 |
----------------
I've tested the value I'm passing, it is being correctly populated from $recId so there's no issue there. Can anyone point me in the right direction as to what's going wrong with this?
Thanks!
NOTE: this works perfectly, but I don't understand why I can't do it with one query:
try{
$query = $con->prepare("SELECT `Id`
FROM `records`
WHERE `id`= :recId
AND `ownerId` = :userId
LIMIT 1");
$query->execute(array('recId' => $recId, 'userId' => $userId));
$rec = $query->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e) {
dump_exception('Exception selecting record.', $e);
}
if($rec){
try{
$picQuery = $con->prepare("SELECT COUNT(`Id`)
FROM `images`
WHERE `parentId`= :recId");
$picQuery->execute(array('recId' => $recId));
$numPics = $picQuery->fetchColumn();
}catch(PDOException $e) {
dump_exception('Exception counting pictures.', $e);
}

Can't you use JOINs and GROUP BY? It would look like this if I got your question right.
SELECT `id`, COUNT(*) AS `numImgs`
FROM `records` r
INNER JOIN `images` i ON i.parentId = r.id
WHERE r.id = :recId
AND r.ownerId = :userId
GROUP BY r.id
LIMIT 1

Looks like I've found the problem thanks to #RyanVincent's comment below. Whilst I have other working queries which use the same parameter more than once without it having to be passed into the "execute" array more than once, in this case, it seems that only listing the parameter once is causing the issue. I suspect that because it's a nested query, it treats it as two independent queries and as such, one has no access to the parameters of another. That's just a guess, I may be wrong, but it seems to make sense based on my results. Not only does the parameter have to be listed twice, but it must also be uniquely named otherwise you get exactly the same problem. So this code fixed the problem:
$query = $con->prepare("SELECT `Id`,
(SELECT count(`Id`)
FROM `images`
WHERE `parentId` = :recIdOne) as `numImgs`
FROM `records`
WHERE `id`= :recIdTwo LIMIT 1");
$query->execute(array('recIdOne' => $recId, 'recIdTwo' => $recId));
$rec = $query->fetch(PDO::FETCH_ASSOC);

Related

MySQL GROUP BY is not working in PDO prepared statement [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 1 year ago.
I have two statements: one is written with mysql_query, another with PDO:
mysql_query:
$sql = $mysql_query("SELECT `user_report`.* FROM `user_report` LEFT JOIN `user` ON
`user_report`.`user_id` = `user`.`user_id` WHERE `user`.`userBlocked` = 0 GROUP BY
`user_id` ORDER BY `reports` DESC, `user_report`.`timestamp` ASC");
PDO prepared:
$sql = $pdo->prepare("SELECT `user_report`.* FROM `user_report` LEFT JOIN `user` ON
`user_report`.`user_id` = `user`.`user_id` WHERE `user`.`userBlocked` = 0 GROUP BY
`user_id` ORDER BY `reports` DESC, `user_report`.`timestamp` ASC");
$sql->execute();
PDO doesn't work with GROUP BY user_id.
Reason I need it is if two results come with the same user_id I want to show it as one.
How is it possible that PDO doesn't allow GROUP BY function ... in MySQL statement is there any substitute to that?
Thank you.
Try this
$sql = $pdo->prepare("SELECT user_report.* FROM `user_report` LEFT JOIN `user` ON
user_report.user_id = user.user_id WHERE user.userBlocked = 0 GROUP BY
user.user_id DESC, user_report.timestamp ASC");
$sql->execute();
changes i did `` removing on selecting tables and
GROUP BY is pointing to which can be (user.user_id or user_report.user_id) you need to confirm?
AND ORDER BY (reports) is pointing to ? so i removed ?
You try the above sql, and provide your output if there is any error.

Php loop all result in next mysql query

i have a small problem. I use two mysql queries for getting data.
First i want to get IDs from groups
$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$IDgroups = $row["ID"];
With that, I'll get those IDs, for example 5, 7, 12, 15, 22
I want to put them all in the next mysql query:
$sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);
When I do this, I get the result only for the first ID (5). And I want for each
I can not INNER JOIN tables because I use this in next query.
I tried with foreach loop, but no effect.
Try this code
SELECT * FROM `orders`
WHERE ID REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)')
ORDER BY `ID` ASC
Just like #Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:
...
$sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC ";
...
Also, confirm if $IDgroups is in the format 1,2,3,4
If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema

Right join cannot access Row from other table in PHP

$query = "SELECT `Title`, `Date`, `Url`, `Url_Hash`
FROM filings
RIGHT JOIN form_attributes ON
filings.Url_Hash=form_attributes.Unique_Hash
ORDER BY filings.Date ASC
$result = mysqli_query( $mysqli, $query);
while ($row = mysqli_fetch_assoc($result)):
$title = row['col_name_in_form_attributes']; // undefined index error
This is pretty basic but has me stuck. I have 2 tables, filings and form_attributes. I want to access the row names of form_attributes, but get an Undefined index error.
As a workaround, I suppose I could do this with STMT like so:
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($result1, $result2, /* etc */);
$stmt->store_result();
However, bind_result() is inefficient as I have over a dozen columns. Much easier to use $row['xyz']; STMT also does not work with MySQL full text search which I am using. Is there a way to do this with mysqli_query or is my SQL incorrect? Thanks.
Not an answer, but FWIW, I find this easier to conceptualise...
SELECT Title
, Date
, Url
, Url_Hash
FROM form_attributes a
LEFT
JOIN filings f
ON f.Url_Hash = a.Unique_Hash
ORDER
BY f.Date ASC
I was forgetting to explicitly call the name of the table plus the column name in my query. Example:
`form_attributes`.`Contact_Info`
Works now!

How to look at the result of a query

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.

MySQL: Error in query with UPDATE and JOIN, when ORDER BY is used

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.

Categories