I want to count and show live users counter on my page. My url structure looks like this domain.com/miningbot?id=pool-v9w1x2y
The users which are inside the parameter should be counted, updated and displayed to the user. Also, the parameter can be changed.
I have asked ChatGPT to write me some starting script and here it is but i don't get the part with the WebSocket

miningbot.html JS:

// Get the id parameter from the URL
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

// Send an AJAX request to increment the visitor count for the id value
const xhr = new XMLHttpRequest();
xhr.open('POST', 'update_visitor_count.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(`id=${id}`);

// Update the live visitor count on the page
const visitorCountElement = document.getElementById('visitor-count');
setInterval(() => {
  fetch(`get_visitor_count.php?id=${id}`)
    .then(response => response.text())
    .then(count => {
      visitorCountElement.textContent = count;
    });
}, 5000); // Update every 5 seconds

get_visitor_count.php

<?php
// Get the id value from the GET request
$id = $_GET['id'];

// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Get the visitor count for the corresponding id value
$sql = "SELECT count FROM visitor_counts WHERE id = '$id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$count = $row['count'];

// Close the database connection
mysqli_close($conn);

// Output the visitor count as plain text
echo $count;
?>

The second PHP code that updates the visitor count in the database should be included in the WebSocket server script that listens for connections and receives messages from the client. (this is the part i don't understand, what should i do?)

<?php
// Get the id value from the POST request
$id = $_POST['id'];

// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Increment the visitor count for the corresponding id value
$sql = "UPDATE visitor_counts SET count = count + 1 WHERE id = '$id'";
mysqli_query($conn, $sql);

// Close the database connection
mysqli_close($conn);
?>

I asked namecheap hosting support they told me this:
Regretfully, it is not possible to install the WebSocket to the shared server. However, you can easily connect to the WebSocket server. For that, you will need to specify the port for the outgoing connection.
It is usually 443, and it is open on our end, but if your application will need any other port, we will open it from our end.

Recommended Answers

All 32 Replies

You can plugin Elfsight to your website to display users count

The code that you copied/pasted here doesn't use websockets. Why do you think it does?

Websockets (which I personally don't have any experience with) let you keep a connection open between the browser and the web server so that the counter is always updated in realtime when the visitor is looking at your page.

In the javascript you're using here, the web browser makes an AJAX request to the server every 5 seconds to update the counter.

@jawass i want to count the total users that are inside a particular page for this example "mining pool". User can create mining pool links and share them, so i want to display to them how much users are currently in their mining pool.
Will that tool help me with this or it will count the all users that are on my main website?

@Dani Yeah this one is cool with the badges code. I prefer more with database and custom made TBH :)

So the PHP code that you have here is definitely just a counter that increments itself by 1 every time someone visits the page, so it doesn't reset itself ever or just show currently active visitors.

miningbot.html JS: Here it looks like we're making an AJAX post request to update_visitor_count.php and sending the value of the ?id= parameter of the current page, and then we're also updating the visitor count every 5 seconds by fetching get_visitor_count.php via AJAX as well.

The problem you have here is in the way the visitor_counts table in the database is structured. As it currently stands, it has two columns: id, and count. Each time a visitor with an id visits, that row's count column is updated.

Typically something like this isn't handled via MySQL (here at DaniWeb we use Redis), but because you're on a shared web server, they probably won't let you install Redis. Therefore, you can make do with MySQL by instead creating a whole new row in the visitor_counts table each time someone visits. The visitor_counts table should have two columns, id and timestamp. Each time someone visits, you could do:

INSERT INTO visitor_counts (id, timestamp) VALUES ('$id', NOW())

Be sure to escape $id first, or use prepared statements, so that you don't introduce an SQL injection attack. Let me know if you're not quite sure how to do that or need some extra help. Here's a little tutorial on how to sanitize PHP user input strings I whipped up.

Anyways, so now we have this table of visitor_counts that has a row for each and every visitor with columns for the id and when they visited.

Now, to get visitor count, we want to take a count of how many rows match the specific id that were created in the past 15 minutes, as so:

SELECT SUM(*) AS count FROM visitor_counts WHERE id = '$id' AND timestamp > NOW() - INTERVAL 15 MINUTE

Again, you will want to be sure to sanitize that $id variable.

Now, and this is the important part, you will need to set up a cron job or a scheduled task or some other way to delete old visitor_counts so the table doesn't grow to an infinite number of rows.

DELETE FROM visitor_counts WHERE timestamp < NOW() - INTERVAL 1 HOUR

Per our live chat, you are a bit confused what I'm referring to.

For now, let's leave miningbot.html alone. I have not confirmed that it should work, but it most likely would. It looks decent enough, although of course you have to have a <div id="visitor-count"></div> element.

Then for get_visitor_count.php, simply do:

<?php
// Get the id value from the GET request
$id = $_GET['id'];

// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Escape the string
$id = mysqli_real_escape_string($conn, $id);

// Get the visitor count for the corresponding id value
$sql = "SELECT SUM(*) AS count FROM visitor_counts WHERE id = '$id' AND timestamp > NOW() - INTERVAL 15 MINUTE";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$count = $row['count'];

// Close the database connection
mysqli_close($conn);

// Output the visitor count as plain text
echo $count;
?>

And for update_visitor_count.php, simply do:

<?php
// Get the id value from the POST request
$id = $_POST['id'];

// Connect to the SQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Escape the string
$id = mysqli_real_escape_string($conn, $id);

// Increment the visitor count for the corresponding id value
$sql = "INSERT INTO visitor_counts (id, timestamp) VALUES ('$id', NOW())";
mysqli_query($conn, $sql);

// If there's no other place for it, you can put it here
$sql = "DELETE FROM visitor_counts WHERE timestamp < NOW() - INTERVAL 1 HOUR";
mysqli_query($conn, $sql);

// Close the database connection
mysqli_close($conn);
?>

Your MySQL database should have a table visitor_counts with two columns: id and timestamp. Remove the count column.

This is great answer and it does update the table, but it doesn't display the count number on the page it self.

On miningbot.html, you currently have:

// Update the live visitor count on the page
const visitorCountElement = document.getElementById('visitor-count');
setInterval(() => {
  fetch(`get_visitor_count.php?id=${id}`)
    .then(response => response.text())
    .then(count => {
      visitorCountElement.textContent = count;
    });
}, 5000); // Update every 5 seconds

Do you have a <div id="visitor-count"></div> element on that page?

commented: Yes i got the <div> element +12

If you use jQuery (which, if I remember correctly, you do), you can do something like this (this code is untested):

<div id="visitor-count"></div>
<script>        
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');
    setInterval(function () {
        $('#visitor-count').load('get_visitor_count.php?id=' + id);
    }, 5000);
</script>

I think the reason that your code doesn't work is because ${id} is PHP, not Javascript.

So now i have in miningbot.html this JS code

<script>
// Get the id parameter from the URL
const urlParamss = new URLSearchParams(window.location.search);
const id = urlParamss.get('id');

// Send an AJAX request to increment the visitor count for the id value
const xhr = new XMLHttpRequest();
xhr.open('POST', 'update_visitor_count.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(`id=${id}`);

// Update the live visitor count on the page
const visitorCountElement = document.getElementById('visitor-count');
setInterval(() => {
  fetch(`get_visitor_count.php?id=${id}`)
    .then(response => response.text())
    .then(count => {
      visitorCountElement.textContent = "LIVE VISITORS: "+count;
    });
}, 5000); // Update every 5 seconds

</script>

When i visit the page it reads the id and saves it in DB with the timestamp, but only once, i am visiting from my phone and Laptop but only one row writes inside the table.

And the visitor-count element doesn't displays the actual number how much people are inside only shows the text 'LIVE VISITORS:'

index.png

It doesn’t add a new row to the table each time you refresh the page?

commented: yes, thats correct +0

Also, that last section is still incorrect. You cannot mix PHP variables into your javascript.

commented: I should replace the JS code i have, with the one you posted? +0

So my database is with unique database index thats why this method dont work. Is there a different solution than this ?

Sorry, I was typing my above messages from my phone while not near a computer.

I am not familiar with using ${id} in Javascript. I typically only see dollar signs in PHP code. I would instead do something like 'get_visitor_count.php?id=' + id

As far as database indexes, you can add indexes to individual tables in your database. If the visitors_counts table has a unique database index preventing multiple rows with the same column from being added, then my method won't work. Remove that index from the table.

I removed it but still doesnt record new value to the table

Ok so i have new approach with cookies and session
miningbot.php file

<div class="live"><span class="visitor-count"><?php include('counter.php'); ?></span></div>
<script>
// Function to update the visitor count using AJAX
function updateVisitorCount() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById('visitor-count').innerHTML = this.responseText;
    }
  };
  xhr.open('GET', 'counter.php', true);
  xhr.send();
}

// Call the updateVisitorCount function every 5 seconds
setInterval(updateVisitorCount, 5000);

// Function to decrement the visitor count when the user leaves the page
window.onbeforeunload = function() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'decrement_count.php', true);
  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  var visitor_id = '<?php echo $visitor_id; ?>';
  xhr.send('visitor_id=' + visitor_id);
};
</script>

counter.php

<?php
session_start();

$db_host = 'localhost';
$db_name = '';
$db_user = '';
$db_pass = '';

try {
  $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
} catch (PDOException $e) {
  die("Database connection failed: " . $e->getMessage());
}

// Get the visitor count from the database
$stmt = $pdo->query('SELECT count FROM visitor_count WHERE id = 1');
$count = $stmt->fetchColumn();

if ($count === false) {
  $pdo->query('INSERT INTO visitor_count (id, count) VALUES (1, 0)');
  $count = 0;
}

// Check if the visitor has a cookie
$cookie_name = 'visitor_id';
if (!isset($_COOKIE[$cookie_name])) {
  // Generate a new visitor ID and set a cookie
  $visitor_id = md5($_SERVER['REMOTE_ADDR'] . time() . rand());
  setcookie($cookie_name, $visitor_id, time() + 3600 * 24); // Cookie expires in 24 hours
  $count++;

  // Insert a new row into the visitors table
  $stmt = $pdo->prepare('INSERT INTO visitors (visitor_id, visit_time) VALUES (?, NOW())');
  $stmt->execute([$visitor_id]);
} else {
  // Check if the visitor has already been counted
  $visitor_id = $_COOKIE[$cookie_name];
  $stmt = $pdo->prepare('SELECT * FROM visitors WHERE visitor_id = ? AND visit_time > DATE_SUB(NOW(), INTERVAL 5 MINUTE)');
  $stmt->execute([$visitor_id]);
  $visitor = $stmt->fetch();

  if ($visitor === false) {
    // Update the visitor count and add a new row to the visitors table
    $count++;
    $stmt = $pdo->prepare('INSERT INTO visitors (visitor_id, visit_time) VALUES (?, NOW())');
    $stmt->execute([$visitor_id]);
  }
}

// Update the visitor count in the database
$stmt = $pdo->prepare('UPDATE visitor_count SET count = ? WHERE id = 1');
$stmt->execute([$count]);

echo "Live miners: $count";

// Include JavaScript to decrement the visitor count when the page is unloaded
echo "
<script>
  window.addEventListener('beforeunload', function(event) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'decrement_count.php');
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send('visitor_id=' + encodeURIComponent('" . $visitor_id . "'));
  });

  // Update the visitor count every 5 seconds using AJAX
  setInterval(function() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          var count = xhr.responseText;
          document.getElementById('visitor-count').innerHTML = count;
        }
      }
    };
    xhr.open('GET', 'counter.php');
    xhr.send();
  }, 5000);
</script>
";
?>

decrement_count.php

<?php
$db_host = 'localhost';
$db_name = '';
$db_user = '';
$db_pass = '';

try {
  $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
} catch (PDOException $e) {
  die("Database connection failed: " . $e->getMessage());
}

if (isset($_POST['visitor_id'])) {
  // Decrement the visitor count in the database
  $stmt = $pdo->query('SELECT count FROM visitor_count WHERE id = 1');
  $count = $stmt->fetchColumn();
  $count--;
  $stmt = $pdo->prepare('UPDATE visitor_count SET count = ? WHERE id = 1');
  $stmt->execute([$count]);

  // Delete the row for this visitor from the visitors table
  $visitor_id = $_POST['visitor_id'];
  $stmt = $pdo->prepare('DELETE FROM visitors WHERE visitor_id = ?');
  $stmt->execute([$visitor_id]);
}
?>

visitors_table.png

visitors_count_table.png

This code is doing good job but the problem is that it increments the count on 5 seconds automaticly AND it doesnt insert the pool id in the DB.

Please if someone can help me with this problem

I don’t understand the logic for this at all. This will only decrement the count if you navigate away by clicking on an external link on your webpage and not if you close your browser window or close out of the browser tab. Also, why does it only work if the visitor_id is 1?

So i come up with new solution and i think it will be the best. Since i have 2 buttons on the page Start mining & Stop mining
I can use them to update the DB correspondingly.
All we need to do is Get the url parameter (id) and add +1 when someone press Start mining or -1 for stop mining

Here is my miningbot page

<button id="start-button" class="btn btn-success mr-2 btn-sm">Start Mining</button>
<button id="stop-button" class="btn btn-secondary mr-2 btn-sm">Stop Mining</button>
<div class="live-indicator">
    <div class="dot"></div>
    <div class="live"><span class="visitor-count">Live miners: </span></div>
</div>

// Start the search when the "Start Mining" button is clicked
    $('#start-button').click(function() {

        // Make an AJAX call to update the database
        $.ajax({
            type: "POST",
            url: "update.php", // Replace with the URL of the server-side script that handles database operations
            data: {id: getParameterByName('id'), action: 'start'}, // Pass the URL parameter value and the action to perform
            success: function(response) {
                console.log(response); // Print the response from the server-side script
            }
        });

    });
    // Stop the search when the "Stop Mining" button is clicked
    $('#stop-button').click(function() {

        $.ajax({
            type: "POST",
            url: "update.php", // Replace with the URL of the server-side script that handles database operations
            data: {id: getParameterByName('id'), action: 'stop'}, // Pass the URL parameter value and the action to perform
            success: function(response) {
                console.log(response); // Print the response from the server-side script
            }
        });
    });

function updateLiveMiners() {
    // Update the visitor count element
    $.get("getVisitorCount.php", function(data) {
        $('.visitor-count').text(`Live miners: ${data}`);
    });

    // Call the update.php script with the appropriate button parameter
    if ($('#start-button').is(':disabled')) {
        $.post("update.php?id=1", { start: true });
    } else if ($('#stop-button').is(':disabled')) {
        $.post("update.php?id=1", { stop: true });
    }
}

GetVisitorCount.php

<?php
// Connect to the database
$servername = "localhost";
$username = "";
$password = '';
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Query the database for the current count of miners
$sql = "SELECT count FROM pools WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$count = $row['count'];

// Return the count as a JSON response
header('Content-Type: application/json');
echo json_encode(['count' => $count]);
?>

update.php

<?php
// Get the id parameter from the URL
$id = $_GET['id'];

// Connect to the database
$servername = "localhost";
$username = "";
$password = '';
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check if the start or stop button was clicked
if (isset($_POST['start'])) {
    // Increment the count column by 1
    $sql = "UPDATE pools SET count = count + 1 WHERE id = $id";
} elseif (isset($_POST['stop'])) {
    // Decrement the count column by 1
    $sql = "UPDATE pools SET count = count - 1 WHERE id = $id";
}

// Execute the SQL statement
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

// Close the database connection
$conn->close();
?>

With this code i don't get any records in the DB and when i click "Start mining" button i get getParameterByName is not defined

I am desperately trying this to work but i dont know why it doesnt insert/update the table ?? :S

here is the updated code in the update.php file

<?php
if (!isset($_POST['id'])) {
    die("Error: id parameter is missing");
}

// Get the id parameter from the URL
$id = $_POST['id'];

// Connect to the database
$servername = "localhost";
$username = "";
$password = '';
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$count = 0;
$sql = "";
$type = "";
$result = $conn->query("SELECT * FROM pools WHERE id = $id");

if ($result && $result->num_rows > 0) {
    // The id exists in the database, execute an UPDATE statement
    if (isset($_POST['start'])) {
        $count++;
        $sql = "UPDATE pools SET count = ? WHERE id = ?";
        $type = "update";
    } elseif (isset($_POST['stop'])) {
        $count--;
        $sql = "UPDATE pools SET count = ? WHERE id = ?";
        $type = "update";
    } else {
        // Return the existing record
        $row = $result->fetch_assoc();
        echo json_encode($row);
        exit();
    }
} else {
    // The id does not exist in the database, execute an INSERT statement
    if (isset($_POST['start'])) {
        $count++;
        $sql = "INSERT INTO pools (id, count) VALUES (?, ?)";
        $type = "insert";
    } elseif (isset($_POST['stop'])) {
        $count--;
        $sql = "INSERT INTO pools (id, count) VALUES (?, ?)";
        $type = "insert";
    } else {
        die("Nothing to do");
    }
}

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die("Error preparing statement: " . $conn->error);
}

$stmt->bind_param("ss", $id, $count);

// Execute the SQL statement
if ($stmt->execute()) {
    if ($type == "update") {
        echo "Record updated successfully";
    } else {
        echo "Record inserted successfully";
    }
} else {
    echo "Error updating/inserting record: " . $conn->error;
}

// Close the prepared statement
$stmt->close();
?>

I get message "Nothing to do" and everything is correct

Have you tried adding console.log() debug statements within each conditional to see if the correct branch of the if-else statement is being triggered each time you hit start/stop?

I actually just discovered a bug such that we haven't been giving the user any alert or warning that their email was unverified.

"live user counters" are a lie! It's technically impossible to create such a thing as you never know whether a user is still actively using the page you're counting them as being on (or indeed the site).

All you can hope for to do is create a counter of the number of times a page was requested over the last say 5 minutes.

Not true. You can use ajax, for example, to enable enough bidirectional communication to ping the server when a user has closed their browser window or clicked away from the webpage.

I actually solved the problem yesterday just i forgot to update the thread

P.S it still have bugs tho...

This is miningbot file

  $('#start-button').click(function() {
        // Make an AJAX call to update the database
        $.ajax({
            type: "POST",
            url: "update.php",
            data: {id: getPoolIdFromUrl('id'), start: true},
            success: function(response) {
                console.log(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });


        intervalId = setInterval(updateStringList, 10); // Update the string list every 0.10 seconds
        $(this).attr('disabled', true); // Disable the button
        $('#stop-button').attr('disabled', false); // Enable the other button
        $('#transfer-button').attr('disabled', true);




    });
    // Stop the search when the "Stop Mining" button is clicked
    $('#stop-button').click(function() {

        // Make an AJAX call to update the database
        $.ajax({
            type: "POST",
            url: "update.php",
            data: {id: getPoolIdFromUrl('id'), stop: true},
            success: function(response) {
                console.log(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });
}
}

this is GetVisitorCount.php file

<?php
// Connect to the database
$servername = "localhost";
$username = "";
$password = '';
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
// Query the database for the current count of miners
$sql = "SELECT count FROM pools WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$count = $row['count'];

// Return the count as a JSON response
header('Content-Type: application/json');
echo json_encode(['count' => $count]);
?>

This is update.php

<?php
if (!isset($_POST['id'])) {
    die("Error: id parameter is missing");
}

// Get the id parameter from the URL
$id = $_POST['id'];

// Connect to the database
$servername = "localhost";
$username = "";
$password = '';
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check if the id exists in the database
$stmt = $conn->prepare("SELECT * FROM pools WHERE id = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // If the id exists in the database, perform an UPDATE operation
    if (isset($_POST['start'])) {
        $sql = "UPDATE pools SET count = count + 1 WHERE id = ?";
    } elseif (isset($_POST['stop'])) {
        $sql = "UPDATE pools SET count = count - 1 WHERE id = ?";
    } else {
        die("Nothing to do");
    }
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $id);
    if (!$stmt->execute()) {
        die("Error updating record: " . $conn->error);
    }
    echo "Record updated successfully";
} else {
    // If the id does not exist in the database, perform an INSERT operation
    $stmt = $conn->prepare("INSERT INTO pools (id, count) VALUES (?, ?)");
    $stmt->bind_param("si", $id, $count);
    if (isset($_POST['start'])) {
        $count = 1;
    } elseif (isset($_POST['stop'])) {
        $count = -1;
    } else {
        die("Nothing to do");
    }
    if (!$stmt->execute()) {
        die("Error inserting record: " . $conn->error);
    }
    echo "Record inserted successfully";
}

// Close the prepared statement
$stmt->close();

// Close the database connection
$conn->close();
?>

What happens if users just keep hitting the start button and then leaving the site and never hit stop? Won’t the counter just keep incrementing indefinitely and then be more and more inaccurate for each user that doesn’t press stop?

commented: Yes thats true and i am trying to figure it out +12

Before he exit the page i warn him with an Alert message i can put the ajax call there so the DB updates for -1 but the thing is it can go below 0 so thats the problem here

can you help me with this one dani ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.