How to Make a Simple Page View Counter using PHP and MySQLi

The code for a counter varies depending on the programming language used and the amount of information you want the counter to collect. If you, like many website owners, use PHP and MySQL with your website, you can generate a simple hit counter for your webpage using PHP and MySQL. You may also like How to count same value in array using php.

PHP Code

    define('DB_SERVER', "localhost");
    define('DB_USER', "root");
    define('DB_PASS', "");
    define('DB_DATABASE', "whatsappdwld_db");
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
    $user_ip = $_SERVER['REMOTE_ADDR'];
    $check_ip = mysqli_query($con,"SELECT userip FROM pageview WHERE page='yourpage' AND userip='$user_ip'");
    if(mysqlI_num_rows($check_ip) == 0)
        $insertview = mysqli_query($con,"INSERT INTO pageview (page,userip)VALUES('yourpage','$user_ip')");
        $updateview = mysqli_query($con,"UPDATE totalview SET totalvisit = totalvisit+1 WHERE page='yourpage' ");

        $stmt = mysqli_query($con,"SELECT totalvisit FROM totalview WHERE page='yourpage' ");
        <p>This page is viewed <?php echo mysqli_num_rows($stmt); ?> times.</p>

Leave a Reply

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