user1431627
user1431627

Reputation: 815

Counting in MySQL

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

Answers (3)

Marcin Majchrzak
Marcin Majchrzak

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

Niet the Dark Absol
Niet the Dark Absol

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

Basic
Basic

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

Related Questions