Reputation: 815
I tried to make a click counter in MySQL, but it dose not seem to work.
Here's my code in PHP (count.php)
<?php
mysql_connect("myhost", "username", "password") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
mysql_query("INSERT INTO `table` (`field`) VALUES(\'+1\'); ")
or die(mysql_error());
?>
And here is the HTML
<html>
<head>
</head>
<div onClick="count.php">Click!</div>
</script>
</body>
</html>
And will this code handle multiple people clicking the button at the same time?
Upvotes: 0
Views: 198
Reputation: 682
onClick is not like href, it shoud look like this:
<div onClick="count()">Click</div>
<script>
function count() {
// java script function that loads count.php by ajax //
}
</script>
in count.php instead of
mysql_query("INSERT INTO table (field) VALUES (1)");
you can use
mysql_query("UPDATE table SET field = field+1 WHERE id = 1");
Upvotes: 4
Reputation: 324620
For a single query that does stuff for you:
INSERT INTO `table` (`Id`, `field`) VALUES (ID_HERE, 1)
ON DUPLICATE KEY UPDATE `field`=`field`+1
This will create a new row if the ID doesn't exist yet, or increase the counter if it does.
Upvotes: 0
Reputation: 26766
Put a single row in your table with an Id of (say) 1
and then do....
mysql_query("UPDATE `table` SET `field`=`field`+1 WHERE Id = 1;");
This will increment the value.
Upvotes: 1