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