Code to count visitors

Its important for some people who own a website to know how many visitors they have. So, today’s code is a php code which allow you to enter every visitor’s information in a table using MySQL

First thing you need to do is creating a new table in your website PhpMyAdmin by copying the following code and paste it the query box.

CREATE TABLE `visitors` (
  `id` int(11) NOT NULL,
  `visitor` varchar(255) NOT NULL,
  `timevisit` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `visitors`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `visitors`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;

Now, the following code is the code that its job to detect every visitor to your website and save the information into the database. The code can be written in a separate file for example “visitors.php” and then you will have to include it the file inside the main page in your website. The second option is to paste the code directly to the main page.

<?php
// This is the code which you can put in a file and call it for example, visitors.php
$SelectVisitors = mysql_query("SELECT * FROM visitors");
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$time = date("m-d-Y h:i");
mysql_query("INSERT INTO `visitors` (`id`, `visitor`, `timevisit`) VALUES (NULL, '".$host."', '".$time."');");
$Total = mysql_num_rows($SelectVisitors);

?>

If you decided to write the code in a separate file, then you have to paste the following code to the main page of your website.

include("visitors.php");

If you want to show the total of visitors use this code:

echo $Total;
coding | php | visitors | web

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart