Ever wanted to create a simple hit counter for your site, but never had the chance to code it yourself? Then, you may simple use the code below — all hard coded by me, royalty-free. The code is used to teach non-techie people how to create PHP-MySQL-driven websites.

<?php
// connect to the MySQL server using 'localhost' as the server name, cPanel username & password
$con = mysql_connect("localhost","cpanelusername","password");
// check if the connection is established or not
if (!$con)  
   {
      die('Could not connect: ' . mysql_error());
   }

// continue with the database processes if the connection is successful
else
   {
      // select the database you wish to connect to
      mysql_select_db("ctrdbase", $con);
      // go to the last record in your database table, this will also be the last number
      $result = mysql_query("SELECT * FROM counter_table ORDER BY ctr DESC LIMIT 1");
      $row = mysql_fetch_array($result);
      // store the last record to a variable
      $cctr = $row['ctr'];
      // declare a new variable that will do the addition thing
      $nctr = $cctr + 1;
      // store the updated counter to the database
      $sql = "INSERT INTO counter_table (ctr) VALUES ($nctr)";
      $dbupdate = mysql_query($sql);
      echo $nctr;
   }
mysql_close($con);
?>

ABOUT THE AUTHOR

Robert “Bob” Reyes is a technologist, an ICT Consultant and Tech Speaker, a certified Google IT Support Specialist, and an Open Source advocate representing the global non-profit Mozilla (makers of Firefox) in the Philippines. Bob is a Technology Columnist for the Manila Bulletin Publishing Corporation and an aviation subject matter expert contributor for Spot.PH.

Follow The Filipino Tech Explainer on Facebook and X/Twitter.

If you liked my articles or any of the contents or if The Filipino Tech Explainer has helped you in any way, you can buy me a coffee and share your thoughts. Help me continue producing awesome articles by supporting my website. Maraming salamat po! Thank you very much!

What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
One thought on “Create a Site Counter Using PHP & MySQL”

Leave a Reply