Reputation: 5
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();
?>
Upvotes: 0
Views: 385
Reputation: 945
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);
[...]
Upvotes: 1