简体   繁体   中英

Php mysql page view counter

I try to make a simple page view counter. Every time the page is refreshed, the number should increase +1.

When I execute the code in Phpmyadmin it all works fine. But in php, the counter is returned, but not incremented. What did I do wrong?

<?php
$username = "username";
$password = "password";
$hostname = "hostname";
$dbname = "dbname";


// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "UPDATE `Games` SET `Played`= `Played`+1 WHERE 'ID'='3'";

$sql = "SELECT `Played` FROM `Games` WHERE `ID` = 3";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    echo "" . $row[Played]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

You have to make a mysqli_query call after you create the UPDATE string into the $sql variable. What you're doing right now is just overriding it with the SELECT query string.

[...]

$sql = "UPDATE `Games` SET `Played`= `Played`+1 WHERE `ID`='3'";

$result = mysqli_query($conn, $sql);

$sql = "SELECT `Played` FROM `Games` WHERE `ID` = 3";

$result = mysqli_query($conn, $sql);

[...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM