Forum Moderators: coopster
Sorry its a lot to ask in one go! Ive basically been asked to modify somone elses code and ive not really seen PHP/MySQL laid out like this before. The code itself doesnt seem to be OO which is why im not understanding the use of -> as ive only ever seen it used in that context.
1. function count_mail() {
2. $recipient = $_SESSION['user_data']->user_id;
3.
4. $sql = mysql_fetch_object(mysql_query("SELECT COUNT(message_id) as howmany FROM mailbox WHERE recipient=$recipient"));
5. if ($sql->howmany >= 1) {
6. $unread = $sql->howmany;
7. return $unread;
8. }
9. else {
10. $unread = '0';
11. return $unread;
12. }
13. }
[edited by: Sonnenblume at 8:02 pm (utc) on Aug. 19, 2007]
Line 4 is getting the query row as an object (as opposed to mysql_fetch_array, assoc, or row). Lines 4, 5, and 6 could be rewritten as:
$sql = mysql_fetch_assoc(mysql_query("SELECT COUNT(message_id) as howmany FROM mailbox WHERE recipient=$recipient"));
if ($sql['howmany'] >= 1) {
$unread = $sql['howmany'];
The AS in the query just tells mysql what name you want to use for the field; it's pretty handy sometimes.
Here's a very very simple analogy of what you're looking at:
Think about a car. Now think about how many tires it has.
For simplicity sake, let's say the car has four tires. In OOP this could be depicted with variables as:
$car->numTires = 4
The command in your sql query: "mysql_fetch_object" is taking the results returned from the query, and turning them into an object. Similar to how "mysql_fetch_array", would turn the results into an array.
So "$sql->howmany" is the number of db entries in the table "mailbox" where the recipient field equals the variable $recipient.
You should invest in a beginning computer science book, and read up about OOP. The "->" terminology is used in most all C based languages (php is one of them), and the OOP methodology is a driving force behind the Java language.
If your programming career progresses, this is not the last time you will see OOP in PHP.
Regards,
-JB