fafchook
fafchook

Reputation: 819

echo clicks count on php button click counter

I found this script in php which counts button clicks and saves them to a txt file.

 <?php
    if( isset($_POST['clicks']) )
    { 
        clickInc();
    }
    function clickInc()
    {
        $count = ("clickcount.txt");

        $clicks = file($count);
        $clicks[0]++;

        $fp = fopen($count, "w") or die("Can't open file");
        fputs($fp, "$clicks[0]");
        fclose($fp);

        echo $clicks[0];
    }
    ?>

    <html>

        <head>

           <title>button count</title>

        </head>
        <body>
            <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
                <input type="submit" value="click me!" name="clicks">
            </form>

        </body>
    </html>

what i cant figure out is how to echo the number of button clicks to a different part of the html. i've tried placing:

 <?php
     echo $clicks[0];
 ?>

but that does not work. what am i doing wrong? thanks..

Upvotes: 3

Views: 9252

Answers (2)

Atli
Atli

Reputation: 7930

I'd suggest separating the part of the code that reads the click count from the part that increments it, so that you can call each part on it's own. Then you don't have to save the click count from the actual incrementation part; you could get the click count on it's own whenever needed, exactly as it exists in the file at that point in time.

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

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

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

With that, you could include the current count at any point in your HTML, by calling the getClickCount function.

    <div>Click Count: <?php echo getClickCount(); ?></div>
</body>

Upvotes: 1

BaBL86
BaBL86

Reputation: 2622

Because of your $clicks[0] is a part of clickInc function.

$clicsCount = 0
if( isset($_POST['clicks']) ) { 
    $clicsCount = clickInc();
}

function clickInc()
{
    $count = ("clickcount.txt");

    $clicks = file($count);
    $clicks[0]++;

    $fp = fopen($count, "w") or die("Can't open file");
    fputs($fp, "$clicks[0]");
    fclose($fp);

    return $clicks[0];
}

than put

<?php echo $clicsCount; ?>

where you need it

Upvotes: 0

Related Questions