how can foreach mysql result?

99 views Asked by At

I have 2 Columns in mysql. valami2 and playerID in table players_extra. I will the following: give 3000 coppers for the first row in valami2, then 2500 coppers for the second(then each row -500 coppers until the 5th place)....after the 5th place give 500 until the 10th place. for the 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

There are 1 answers

0
colefner On BEST ANSWER

Try PDO. It's a much better and safer way of interacting with databases for 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++;
}