randomgap top-rss

random things from random places

This was one of my first script that I made using php and mysql. It’s pretty short and straight forward. It’s a simple counter script. I know if you google it, you will get thousands of them.

Well, Lets get started.

Step 1: Creating a Table for your counter in MySQL

First thing you need to do is to have a database and have a MySQL table for your counter. I’m going to assume you already have a database to work with so I’ll take it from creating a table for your database. I use PHPmyAdmin to manage my databases.

In your database, run this SQL syntax;

CREATE TABLE mycounter
(
counter int
)

This will create a table named “mycounter” and a column named “counter“. Next step is to set your counter zero or to some other number you want. Here is SQL Syntax for it;

INSERT INTO mycounter (counter)
VALUES (0)

This will set counter column in your “mycounter” table to “0″. If you want your counter start with a different number, replace “0″. You can also use this SQL syntax to reset or change it.

Step 2: Getting the Value and Updating it

Next thing to do is to get the current value and update it every time your page reloads.

Here is the PHP code, put this in your PHP file;

//configs
$dbhost = 'yourhost';
$dbuser = 'yourusername';
$dbpass = 'yourpass';
$dbname = 'yourdb';//connects to your database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
//gets current value
$query = "SELECT * FROM mycounter";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$cont=$row['counter'];
$new = $cont + 1;
//prints out the updated value from last update
echo $new;
//updates your column with the new value
mysql_query("UPDATE mycounter SET counter = '$new'");
//close connection
mysql_close($conn);

That’s it you are done. Save your file and run it. If you did everything correct, it should work properly. It does for me. Again, I’m not a PHP Master or anything like it. I don’t guarantee anything. This is what I have for my website. It works fine. As said above, there are tons of ways to accomplish something using PHP. I did one of them.