I am assuming that each foid
represents a gallery:
SELECT foid, uid, date,
(CASE WHEN pic1 IS NULL THEN 0 ELSE 1 END +
CASE WHEN pic2 IS NULL THEN 0 ELSE 1 END +
CASE WHEN pic3 IS NULL THEN 0 ELSE 1 END
) AS pic_count
FROM foto
WHERE uid = $id
ORDER BY foid DESC
Incidentally, this isn't a particularly sensible way to structure your schema. You really should split the pics out as a separate table:
foto:
foid | uid | date
-----------------------
104 | 5 | 2010-01-01
105 | 14 | 2009-04-08
106 | 48 | 2010-08-09
pic:
foid | pic
------------
104 | 1.jpg
104 | 2.jpg
104 | 3.jpg
105 | 8.jpg
106 | x.jpg
106 | y.jpg
Now, galleries can have more than three pics and querying is simpler:
SELECT foid, uid, date, COUNT(*)
FROM foto
JOIN pic USING (foid)
WHERE uid = $id
ORDER BY foid DESC
GROUP BY foid, uid, date
EDIT: You can split an existing database thus (just guessing at stuff like column types):
CREATE TABLE picture (foid INT, pic VARCHAR(255));
INSERT INTO picture (foid, pic)
SELECT foid, pic1 as pic FROM foto WHERE pic IS NOT NULL
UNION
SELECT foid, pic2 as pic FROM foto WHERE pic IS NOT NULL
UNION
SELECT foid, pic3 as pic FROM foto WHERE pic IS NOT NULL
;
ALTER TABLE foto
DROP COLUMN pic1,
DROP COLUMN pic2,
DROP COLUMN pic3
;
Obviously, one should exercise considerable care when dropping columns, and make a backup before you start!