I need help on this. Will really appreciate it. I am sending an array from an endpoint to my model to fetch the count of each item in my array, If I do a simple selection of all or some of the columns in my table, I get all the results. If I combine a selected column and the count() I get the count of all the items in the table
$sql = "SELECT barcode, (SELECT count(barcode) bcnt FROM shelves) as bcount FROM shelves WHERE barcode IN ('".implode("','",$data['barcode'])."')";
$statement = $this->connection->prepare($sql);
$statement->execute();
$row = $statement->fetchAll();
$this->response['data']=$row;
$this->response['error_code']=0;
$this->response['status']='success';
$this->response['message']='data retrieve for shelves';
{
"error_code": 0,
"status": "success",
"message": "data retrieve for shelves",
"error_message": "",
"data": [
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "5902280031062",
"bcount": "1485"
},
{
"barcode": "133",
"bcount": "1485"
}
]
}
if I use count() only I get only one result.
$sql="SELECT count(*) FROM shelves WHERE barcode IN ('".implode("','",$data['barcode'])."')";
{
"error_code": 0,
"status": "success",
"message": "data retrieve for shelves",
"error_message": "",
"data": [
{
"count(*)": "15"
}
]
}
You need to use
GROUP BYwhen counting so SQL can properly count for each barcode.In your first example it is counting all barcodes in separate
SELECTand displays only the ones that are inIN()condition. And then it returns that full count for every row where barcodes inIN()condition exist.In second example you are actually counting it fine but you are not returning barcodes. To do that you need to select and group them.
Your query would then look something like this: