php mysql页面查看计数器

时间:2015-04-07 14:13:50

标签: php mysql

我尝试制作一个简单的页面查看计数器。 每次刷新页面时,数字都应增加+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();
?>

1 个答案:

答案 0 :(得分:1)

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);

[...]