In this tutorial / code example we will show you how to build a simple counter using a MySQL database . This database will be called counter , it will contain one table called counter which will in turn contain one field called count.
Start MySQL and at the command prompt type the following
CREATE database counter;
USE counter;
CREATE table counter(count int(10) DEFAULT '0' NOT NULL);
This creates our MySQL database . Now for the script to access the count and display this on our web page.
Replace hostname , username and password with your own details
Code: Select all
<?php
//make a connection
$connection = mysql_connect("hostname","username" ,"password")
or die ("Cannot make that connection");
//connect to our database
$db = mysql_selectdb("counter" , $connection);
//store the result of the query in $result
$result = mysql_query("SELECT * FROM counter");
//retrieve the fields in our table
$fields = mysql_fetch_row($result);
//update the count field by 1
mysql_query("UPDATE counter SET count = count+1");
//$mycount variable is set to the first field (count)
$mycount = $fields[0];
//display the count
echo $mycount;
?>