StdClass Object, getting the value

StdClass Object, getting the value

by Alexander De La Garza -
Number of replies: 3

Good day,

I am trying to make a custom dashboard on moodle to see how many users have viewed a page. (I am new to PHP so pls bare with me)

My SQL comand works fine in PHP my admin, and it works in my PHP file,

but when I view it I only see the following:

stdClass Object
(
    [count(id)] => 108
)
I only want the 108 .... to put in a table
I tried:
$test = get_object_vars($countVisits);
echo $test  . "<br><br>";
but this just outputs its an array,

$countVisits[0]; gives me an error,
$countVisits->count(id); comes out blank
thanks!
--- CODE ---

$sql = "SELECT COUNT(id) FROM `m_logstore_standard_log` WHERE `courseid` = 98 AND (`timecreated` Between $startDateU AND $endDateU) AND (`contextinstanceid` = 399 OR `contextinstanceid` = 397)  AND `action` = 'viewed';";

$countVisits = $DB->get_record_sql($sql, null);

print_object($countVisits);

Average of ratings: -
In reply to Alexander De La Garza

Re: StdClass Object, getting the value

by Alexander De La Garza -
Finally found my answer! hope this helps any future noobs

$countVisitsValue = $countVisits->{'count(id)'};
echo($countVisitsValue);
In reply to Alexander De La Garza

Re: StdClass Object, getting the value

by Mark Johnson -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

You can make this easier by adding an alias to your SQL query for that field. SELECT COUNT(id) AS count FROM... will let you do $countVisits->count to access the result. You can also use $DB->count_records_sql() which will just return the numeric result.

As an aside, I would strongly recommend you read the Data Manipulation API documentation, particularly the sections on table prefixes and placeholders. These will help you avoid introducing security and portability issues in your code.

Average of ratings: Useful (1)