我正在制作一个简单的网站,每当有人点击这个链接时,我都会计数,我对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");
}我的DB (命名为'Recorder')是设置在其中有两个表:“目标”和“视图”,每个表都有一个名为“计数”的行。
这里可以看到我的数据库是什么样子的:
|---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");
}发布于 2013-10-27 23:37:05
下面的代码应该可以做到这一点。
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 *,除非您真的要使用all字段。
选择您想要的字段。
select v.counts from recorder.views v where ......请停止使用过时和不安全的mysql_库。
使用pdo代替您的代码将更干净、更高效和最重要的是避免sql注入。请参阅: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. https://stackoverflow.com/questions/19624895
复制相似问题