tags:

views:

358

answers:

2

Hi

I have a simple table as below.

CREATE TABLE `stats` (
  `id` int(11) NOT NULL auto_increment,
  `zones` varchar(100) default NULL,
  `date` date default NULL,
  `hits` int(100) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

So just storing simple hits counter per zone per day.

But I just want to increment the hits value for the same day.

I have tried the MYSQL DUPLICATE KEY UPDATE but this wont work as I may have many zones on different dates so I cant make them unique or dates.

So the only way I can think is first to do a query to see if a date exists then do a simple if() for insert/update

Is their a better way of doing such a task as there maybe be many 1000's hits per day.

Hope this makes sense :-).

And thanks if you can advise.

+1  A: 
$result = mysql_query("SELECT id FROM stats WHERE zone=$zone AND date=$today LIMIT 1");
if(mysql_num_rows($result)) {
    $id = mysql_result($result,0);
    mysql_query("UPDATE stats SET hits=hits+1 WHERE id=$id");
} else {
    mysql_query("INSERT INTO stats (zone, date, hits) VALUES ($zone, $today, 1)");
}

Something like that, if I've interpreted you correctly... that's completely untested. You can figure out what the variables are.

Mark
This solution suffers from a potential race condition.
Martin Spamer
Then use the better solution above :p Didn't think about that. Good call ;)
Mark
+7  A: 

Declare the tuple (zone, date) as unique in your CREATE statement. This will make INSERT ... ON DUPLICATE UPDATE work as expected:

CREATE TABLE `stats` (
  `id` int(11) NOT NULL auto_increment,
  `zone` varchar(100) default NULL,
  `date` date default NULL,
  `hits` int(100) default NULL,
  PRIMARY KEY  (`id`),
  UNIQUE (`zone`, `date`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

INSERT INTO stats (zone, date, hits) values ('zone1', 'date1', 1) ON DUPLICATE KEY UPDATE hits = hits + 1;
Ayman Hourieh
Lee
UNIQUE(zone, date) ensures that zone and date are unique *together*. It is perfectly fine to have multiple entries with the same zone as long as dates are different. The same applies to multiple entries with the same date and different zones. But there must not be two entries with the same zone *and* date. I think this matches your requirements. Give it a try in a test database and see if it works.
Ayman Hourieh
Ill try again Ayman.I had excatly what you had above but ill try again now.
Lee
OK I know what was the problem I had.I hade 2 unique names for each unique field ie.KEY `zone` (`zone`),KEY `date` (`date`)So working perfect. I was close but Thank you.
Lee