PDO, fetched rows and the fastest way...

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
asgerhallas
Forum Commoner
Posts: 80
Joined: Tue Mar 14, 2006 11:11 am
Location: Århus, Denmark

PDO, fetched rows and the fastest way...

Post by asgerhallas »

I have a SELECT query that get one or more rows from a large table. The script must do different things if the result is either 0, 1 or 2 and more rows. I'm using PDO and is has no function like mysql_num_rows() ... what must I do then?

I thought about running a second query with COUNT(*), but is that efficient? Or is it better to do a count(fetchAll())?

Does anybody know the best way to do it?

/Asger
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If you're going to always work on all the records returned, storing the results in an array and counting them like your second idea is fine, otherwise using a COUNT() may be better.
asgerhallas
Forum Commoner
Posts: 80
Joined: Tue Mar 14, 2006 11:11 am
Location: Århus, Denmark

Post by asgerhallas »

Ok, thanks!

Does that COUNT(*) need to be in another query, or is there a smart way to have it as a row in the same query?
I've tried this:

Code: Select all

SELECT *, COUNT(*) cnt FROM table WHERE name='somename'
But it wants the GROUP BY in it - and I can't find out what to GROUP BY - any idea?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

That query likely won't work the way you'd like it to. Best case, if you insist on getting the count in the same query is using a UNION.
asgerhallas
Forum Commoner
Posts: 80
Joined: Tue Mar 14, 2006 11:11 am
Location: Århus, Denmark

Post by asgerhallas »

Ok... thank you very much!

/Asger
Post Reply