0

I'm trying to get the number of images in each gallery by using the below query in a foreach statement

$total = $connect->query("SELECT COUNT(*) FROM photos WHERE gallery = '$row[id]'");

To print this out I'm then using $total[0] which returns Array - how do I retrieve the number?

7
  • 1
    query()-functions usually return a resource, not an array. Without knowing what kind of object $connect is, we can't know. Commented Aug 26, 2013 at 23:16
  • Whats echo '<pre>'.print_r($total,true).'</pre>'; look like? Commented Aug 26, 2013 at 23:18
  • 1
    Obligatory SQL Injection Humor Link (with a serious point). Commented Aug 26, 2013 at 23:19
  • @FaceOfJock: Is that like the Face of Boe? Commented Aug 26, 2013 at 23:21
  • @T.J.Crowder I use PDO prepare statements in my db class, that should protect me from 1st order injection right? I'm still getting the hang of MySQL etc. :L Commented Aug 26, 2013 at 23:37

4 Answers 4

2

Do this:

$total = $connect->query("SELECT COUNT(*) as nImages FROM photos WHERE gallery = '$row[id]'");

then you can read it like this

$total[0]["nImages"]
Sign up to request clarification or add additional context in comments.

Comments

1

if $connect is mysqli object:

$total = $connect->query("
    SELECT COUNT(*) AS `count` FROM photos WHERE gallery = '$row[id]'
")->fetch_assoc();

// $total['count']

Notice: Use PDO library and param binding to prevent sql injections.

Comments

0

you can alternatively use fetchColumn instead of query

Comments

0

I had the same issue, and oddly enough the array key was the COUNT(*) text so I litterally have to reference it to get the value I wanted.

[allUsers] => Array
                (
                    [0] => Array
                        (
                            [COUNT(*)] => 606
                        )

                )

In order to access it I literally had to access the array key.

$selectResult[0]['COUNT(*)']; 

Array
(
    [savedInfo] => Array
        (
            [allUsers] => 606
        )

)

Only thing to note is, to program this strongly so you dont run into an error, when I am saving the data I look to see if the original response is an array or not. So not sure if this fix is dirty or not.

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.