Skip to content

Instantly share code, notes, and snippets.

@prosantamazumder
Last active April 5, 2020 12:10
Show Gist options
  • Save prosantamazumder/393509700283aa61e288205b3d196cfe to your computer and use it in GitHub Desktop.
Save prosantamazumder/393509700283aa61e288205b3d196cfe to your computer and use it in GitHub Desktop.
PHP – MySQL visitor counter
<?php
$servername = "localhost";
$username = "dbuser";
$password = "dbpassword";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Counter SET visits = visits+1 WHERE id = 1";
$conn->query($sql);
$sql = "SELECT visits FROM Counter WHERE id = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$visits = $row["visits"];
}
} else {
echo "no results";
}
$conn->close();
?>
=============================== DISPLAY FRONTEND
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Visit counter custom php website</title>
</head>
<body>
<!-- USE THE CODE -->
Your Website Visitor: <?php echo $visits; ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment