Tech4Wilco
Tech4Wilco

Reputation: 6818

Counter does not increment in PHP/MySQL

I need to create a counter for member section (count the number of times a user logged).

I have the following script (counter.php):

<?php
    $conn = mysql_connect("localhost", "myuser", "mypass");
    mysql_select_db("test");

    $sql = "SELECT views FROM members WHERE mid = " . $_GET['mid'];     
    $result = mysql_query($sql); 
    if (!$result)
        {
        mail(ADMIN, 'Cannot Get: ' . mysql_error(), mysql_error());  
        }
    while ($row = mysql_fetch_assoc($result)) 
        {
        $count = $row['views']++; 
        }
    $query = "UPDATE members SET views = '$count' WHERE mid = " . $_GET['mid']; 
    mysql_query($query); 
    mysql_close($conn);

    // show the logo using header() and readfile(); // that part work
?>

DB:

CREATE TABLE `members` (
  `mid` int(11) NOT NULL AUTO_INCREMENT,
  `views` int(11) DEFAULT '0',
  /* etc...*/
  PRIMARY KEY (`mid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Now, what I do in my .htaccess file is:

RewriteEngine On
RewriteRule ^img/logo([0-9]+).jpg$ /counter.php?mid=$1 [L]

but for some reason my counter does not count correctly. What am I missing?

Upvotes: 5

Views: 573

Answers (3)

endyourif
endyourif

Reputation: 2202

You could probably just simplify it and do the following:

$query = "UPDATE members SET views = views + 1 WHERE mid = " . $_GET['mid']; 
mysql_query($query); 

if (mysql_affected_rows() == 0) {
   mail(ADMIN, 'Cannot Get: ' . mysql_error(), mysql_error());
}

mysql_close($conn);

No need to do initial check.

Upvotes: 12

GolezTrol
GolezTrol

Reputation: 116200

The problem is in the line

$count = $row['views']++; 

This actually says:
- Assign the value of view to $count
- Increment views.

But you want:

$count = ++$row['views']; 

Which says:
- Increment views.
- Assign the (incremented) value of view to $count

A subtle difference. :~)

Upvotes: 2

Peter
Peter

Reputation: 16943

use this

$count = $row['views'] + 1;

or

$count = ++$row['views'];

or

$query = "UPDATE members SET views = views + 1 WHERE mid = " . $_GET['mid'];

syntax:

$x = 1;
$count = $x++;
// $count = 1

$x = 1;
$count = ++$x;
// $count = 2

Upvotes: 5

Related Questions