0

I want to count the number of images with prefix PublicImg from different two tables, so I used this code:

    $nb_imgs_a_afficher = $BDD->query("
                                    SELECT COUNT(ID,img_kind) 
                                    FROM images_public  

                                    UNION

                                    SELECT COUNT(ID,img_kind) 
                                    FROM images_users  

                                    WHERE img_kind='PublicImg'");

    $images_users = $nb_imgs_a_afficher->fetch();

But I receive this error:

( ! ) Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' in C:\wamp1\www\website\Index_Public_Images\public_images.php on line 72

Well, before I had one table that was easy with:

$nb_imgs_a_afficher = $BDD->query("SELECT COUNT(*) AS nb_imgs FROM images_users WHERE img_kind='PublicImg'  ");
2
  • SLECET might be a problem here. Commented Sep 17, 2013 at 15:37
  • SELECT COUNT ... + SELECT COUNT ... ? I think you need the plus operator (+) instead of UNION Commented Sep 17, 2013 at 15:38

1 Answer 1

1

Firstly, you have a typo there. Change SLECET to SELECT and then if you are trying to get a sum of rows from two different table use -

SELECT COUNT(*) FROM (
    SELECT ID,img_kind
            FROM images_public  
            UNION
    SELECT ID,img_kind
            FROM images_users  
            WHERE img_kind='PublicImg' ) x

Not sure if you meant to have the WHERE clause on both queries. If so, add WHERE img_kind='PublicImg' before the UNION as well.

Also, check for duplicates. UNION removes duplicates where as UNION ALL doesn't.

Sign up to request clarification or add additional context in comments.

Comments

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.