0

I have a PHP function that looks like this:

function count_creatives() {
    global $db;
    $q = "SELECT COUNT(DISTINCT creative) FROM actions";
    return $db->query($q);
}

The $db variable contains a PDO object and is set correctly (used successfully elsewhere).

When I try to assign the result of this function to a variable, it only contains the querystring (no results).

Code I'm Running:

$count = count_creatives();

echo $count;

Output:

PDOStatement Object ( [queryString] => SELECT COUNT(DISTINCT creative) FROM actions )

Any idea why I'm not getting the actual count (e.g. 2, 3, 100)?

2 Answers 2

1

You're returning the resource object from your function, not the field value. You need to fetch the result and then return that. Please use the following:

function count_creatives() 
{
    global $db;
    $q = "SELECT COUNT(DISTINCT creative) AS `total` FROM actions";
    $result = $db->query($q);
    $actions = $result->fetchObject();

    return $actions->total;
}
Sign up to request clarification or add additional context in comments.

Comments

1

PDO::query() returns a PDOStatement object, or FALSE on failure. You need to do something like,

function count_creatives() {
    global $db;
    $q = "SELECT COUNT(DISTINCT creative) FROM actions";
    $query = $db->query($q);
    return $query->fetch(PDO::FETCH_NUM)[0];
}

1 Comment

count_creatives() will return an array, not the count.

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.