0

我正在制作一个简单的网站,每次有人点击链接时都会计数,我是 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");
}

我的数据库(名为“记录器”)设置在我有 2 个表的位置:“目标”和“视图”每个表都有一个名为“计数”的行

这是我的数据库的外观:

                    |---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");
}
4

1 回答 1

0

下面的代码应该可以解决问题。

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-injection 影响。见: 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. 
于 2013-10-27T23:37:05.637 回答