Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP click counter

I have a .php script that counts the clicks of a button and places them into a .txt file, all fine here but what I have now only works on a single count. If, let's say, I make two buttons, it will show the same number of clicks for both of them.

I need the script to work foreach button separately...

PHP:

if( isset($_POST['clicks']) ) { 
    incrementClickCount();
}

function getClickCount()
{
    return (int)file_get_contents("clickit.txt");
}

function incrementClickCount()
{
    $count = getClickCount() + 1;
    file_put_contents("clickit.txt", $count);
}

HTML:

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="submit" value="click me!" name="clicks">
</form>
<div>Click Count: <?php echo getClickCount(); ?></div>
like image 492
Alin Avatar asked Oct 26 '25 03:10

Alin


1 Answers

You should try different approach, I think. First, saving clicks in file is slower than in database, so you should use a database instead of file.

Then, you can create a table, with button_id field and corresponding click_number field. So if button with id="1" is clicked you increment click_number value for that button.

like image 166
Damaged Organic Avatar answered Oct 28 '25 17:10

Damaged Organic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!