我正在制作一个简单的网站,每次有人点击链接时都会进行计数,我是 PHP 和 MySQL 的新手,但我有基础知识。所以,我在制作“目标计数器”时遇到了问题,所以可以说我的目标设置为 700 次观看。该页面的浏览量为 500 次。当观看次数达到 700 时,我希望目标提高 200。所以它会是 900,我希望每次观看次数达到目标时都会发生这种情况。这就是我尝试的方法:
$goalQuery = mysql_query("SELECT * FROM goal");
$goalRow = mysql_fetch_assoc($goalQuery);
if($viewNewCounts == $goal) {
$goalCounts = $goalRow['counts'];
$goalNewCounts = $goalCounts + 200;
$goalUpdate = mysql_query("UPDATE `Recoreder` . `goal` SET `counts` $goalNewCounts");
}
我的数据库(名为“记录器”)设置为有两个表:“目标”和“ View ”,每个表都有一行名为“计数”
这是我的数据库的外观:
|---counts
|---views|
---Recorder| [Tables] [Rows]
|---goal |
|---counts
我的计数器代码如下所示
注意:它工作正常,我的计数器没有出现问题,我的目标有问题
$viewQuery = mysql_query("SELECT * FROM views");
while($viewRow = mysql_fetch_assoc($viewQuery))
{
$viewCounts = $viewRow['counts'];
$viewNewCounts = $viewCounts + 1;
$viewUpdate = mysql_query("UPDATE `Recorder` . `views` SET `counts` = $viewNewCounts");
}
最佳答案
下面的代码应该可以解决问题。
Php:
if ((($counts -100) % 200) === 0) { do the update statement
SQL:
update recorder.goal g set g.counts =
(select v.counts from recorder.views v where .....)
where .....
代码注释
您的代码很差,原因如下:
除非您确实要使用所有字段,否则切勿使用 select *。
选择您想要的字段。
select v.counts from recorder.views v where ......
请停止使用过时且不安全的 mysql_ 库。
使用 pdo 代替,你的代码会更干净、更高效,最重要的是可以避免 sql 注入(inject)。请参阅:http://php.net/manual/en/book.pdo.php
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch(PDOException $e) {log the error and die}
$sql = "select v.counts from recorder.views v where player = ?";
$statement = $conn->prepare($sql);
$statement->execute(array(100));
$vcounts = $statement->fetchColumn(0);
....
$conn = null; #clean up connection not needed for long periods.
关于PHP 和 MySQL 计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624895/