循环直到变量达到0

时间:2014-03-27 17:48:57

标签: php mysql

我有一个查询,它给出了使用计数的出现次数,见下文:

$query = "SELECT COUNT(a.market_id) AS winners, a.winner, 
a.twitter_pubstatus, a.market, a.racetime, a.racecourse, b.course, b.horse, 
b.type, b.racetime FROM results a INNER JOIN bets b ON a.racecourse = b.course 
WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND 
b.type = '$userwin' AND a.winner = b.horse;";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$checkWinners = $row['winners'];

echo $checkWinners;

这例如将返回11.我现在有一个IF语句:

<?php if ($checkWinners > 1) { ?>

DO THIS

<? } else { ?>

DO THIS INSTEAD

<? } ?>

现在它经历了这一次,那很好。我希望它循环通过,11然后通过第一位然后需要它将是10并经历直到它达到0然后停止。

怎么做?而Loop?帮助感谢

3 个答案:

答案 0 :(得分:1)

是的,您可以使用while循环执行此操作。基本逻辑是:

$c = 10;
while ($c > 0) {
  // do something
  $c--;
}

但如果我不得不猜测,我想也许你真正想要的是这个:

$query = "SELECT COUNT(a.market_id) AS winners, a.winner, 
a.twitter_pubstatus, a.market, a.racetime, a.racecourse, b.course, b.horse, 
b.type, b.racetime FROM results a INNER JOIN bets b ON a.racecourse = b.course 
WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND 
b.type = '$userwin' AND a.winner = b.horse;";
$result = mysql_query($query) or die(mysql_error());

while ( $row = mysql_fetch_array($result) ) {
  $checkWinners = $row['winners'];
  echo $checkWinners . '<br/>';
}

这将遍历查询返回的所有行。

答案 1 :(得分:0)

while($checkWinners >0){

 echo $checkWinners;
 $checkWinners--;
}

答案 2 :(得分:0)

更简单的方法是正常循环,让MySQL根据需要对它们进行排序,以确保它们的顺序正确。

$query = "SELECT COUNT(a.market_id) AS winners, a.winner, 
    a.twitter_pubstatus, a.market, a.racetime, a.racecourse, b.course, b.horse, 
    b.type, b.racetime FROM results AS a INNER JOIN bets AS b ON a.racecourse = b.course 
    WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND 
    b.type = '$userwin' AND a.winner = b.horse
    ORDER BY winners DESC;"; //<--- ORDER BY 
$result = mysql_query($query) or die(mysql_error());

if( mysql_num_rows( $result ) ) { //Check if there's any results
    while ( $row = mysql_fetch_array($result) ) { //Iterate results until empty
        $checkWinners = $row['winners'];
        //Tweet winners code here
        echo $checkWinners . '<br/>';
    }
    //Update database to reflect the updated tweets
    $query = "UPDATE results AS a INNER JOIN bets AS b ON a.racecourse = b.course 
        WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND 
        b.type = '$userwin' AND a.winner = b.horse
        SET a.twitter_pubstatus = 1;" //Update all of them at once
    mysql_query($query) or die(mysql_error()); //Send query, unless fail
} else {
    //If no results from initial query
    echo "No Winners! :(";
}

此外,您应该考虑在 mysql 上使用 mysqli ,因为不推荐使用PHP的mysql扩展。请参阅:Why shouldn't I use mysql_* functions in PHP?