0

I'm having issues getting 2 different row counts by using a conditional statement.

$sql = select sum(id = :id AND category = :cat) as count1, 
              sum(category = :cat) as count2 
       from furniture;
$stmt = $connectdb->prepare($sql);
$stmt->execute(array(':id'=>$id, ':cat'=>"1"));
$resulta = $stmt->fetchAll(PDO::FETCH_ASSOC);

$rowCount1 = count(count1);
$rowCount2 = count(count2);

How do I get the count value of count1 or count2?

3 Answers 3

1

I would probably do this. By the way, props to you for SUMming in SQL and not doing a horrible loop after :)

$resulta = $resulta[0];

$rowCount1 = $resulta['count1'];
$rowCount2 = $resulta['count2'];
Sign up to request clarification or add additional context in comments.

Comments

1

You can use fetch instead of fetchAll because your result will only contain 1 record:

$resulta = $stmt->fetch(PDO::FETCH_ASSOC);

To access that record do:

$rowCount1 = $resulta['count1'];
$rowCount2 = $resulta['count2'];

Besides that you need quotes around your query, and you need a where clause for your query:

$sql = "select sum(id) as count1, sum(category) as count2 from furniture where id = :id AND category = :cat";

However I doubt if this results in the desired result.

4 Comments

This solution would, unless I'm mistaken, leave both $rowCount1 and $rowCount2 as 1, because both $resulta['count1'] and $resulta['count2'] will both be of length 1? So you can get rid of the use of count() here, I'd wager.
Thanks. Looks good. My original query was "SELECT cutID FROM furniture WHERE cutID = :custID AND category = :cat"; I chnaged it to the above coz I needed to get two count values from it. In my above query I've omitted WHERE cutID = :custID AND category = :cat will that change the output?
@d0ug7a5 True removed the count.
@Bekki - the WHERE clause can be whatever you want, that shouldn't affect SQLs ability to return the sum values - it will look at cutID and category, just not return them :)
0

The ->fetchall() method returns an array of result rows so you would have to do

$rowCount1 = $resulta[0]['count1'];
$rowCount2 = $resulta[0]['count2'];

Alternatively when you know there will only be one result row use

$resulta = $stmt->fetch(PDO::FETCH_ASSOC);
$rowCount1 = $resulta['count1'];
$rowCount2 = $resulta['count2'];

Just as an adendum, I have no idea what that query is doing or even if it would work!

2 Comments

I like the second of these :) don't forget $rowCount2 mind ;)
$rowCount2 yup fixed it. Copy/Paste... the devils concept

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.