我尝试做一个简单的页面浏览计数器。
每次刷新页面时,数字应增加+1。
当我在Phpmyadmin中执行代码时,一切正常。但是在php中,该计数器会返回,但不会增加。我做错了什么?
<?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();
?>
最佳答案
在mysqli_query
变量中创建UPDATE字符串后,必须进行$sql
调用。您现在正在做的只是用SELECT查询字符串覆盖它。
[...]
$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);
[...]