如何foreach mysql结果?

时间:2018-02-10 19:34:15

标签: php mysql

我在mysql中有2个列。表player_extra中的valami2和playerID。 我将以下内容: 为valami2中的第一行提供3000个铜币,然后为第二行提供2500个铜币(然后每行-500个铜币直到第5个位置)....在第5个位置后给500个直到第10个位置。对于CORRECT payerID。

            $aseco->console('>> Updating `hetimostfin` counts for all Players...');
        $hetimostfin = array();
        $line = 0;
        $coppers = 3000;
        $query = "
        SELECT
            `playerID`,
            COUNT(`valami2`) AS `Count`
        FROM `players_extra`
        GROUP BY `playerID`;
        ";
        $res2 = mysql_query($query);
        if ($res2) {
            if (mysql_num_rows($res2) > 0) {
                while ($row = mysql_fetch_object($res2)) {
                    $hetimostfin[$row->playerID] = $row->Count;
                }
                foreach ($hetimostfin as $id => $count) {
                    $res2 = mysql_query("
                        UPDATE `players_extra`
                        SET `valami2` =(`valami2`+'".$coppers."')
                        WHERE `playerID` = ". $id ."
                    ");
                    $line ++;
        $coppers=($coppers-500);

        if ($line >= 6) {
            $coppers=500;
        }
        if ($line == 10){
            break;
        }
        }
        }
        }

1 个答案:

答案 0 :(得分:0)

尝试PDO。它是与PHP数据库交互的更好,更安全的方式。 http://php.net/manual/en/pdo.connections.php

$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$hetimostfin = array();
$coppers = 3000;
$line = 0;

$query = <<<SQL
SELECT 
   playerID, 
   COUNT(valami2) AS `count`
FROM players_extra
GROUP BY playerID;
SQL;

foreach($dbh->query($query, PDO::FETCH_ASSOC) as $row) {
    $hetimostfin[[$row['playerID']] = $row['count'];
    // execute update statement
    $line++;
}