简体   繁体   中英

FOR looping while grabbing part of the data from $_POST

It has been awhile since I have messed with for loops and was wondering if this is possible: Here is what I have:

$mn = $_POST['mnpoints'];                   
$mi = $_POST['mipoints'];
$in = $_POST['inpoints'];
$wi = $_POST['wipoints'];

These grab numbers from a form once the submit button is clicked it will the use the following code to update the MySQL database

for ($i = 0; $i <=4; $i++ )
{
  mysql_query("UPDATE " . $db_table . " SET `score` = `score` + <VARIABLE HERE> WHERE id=$i") or die (mysql_error());
}

What would be the best way to accomplish this? I can always change the variables to be $m1 - $m4 and the just use $m$i

Just wondering if there is another way or a better way Thanks

Put your variables into an array:

$values = array($mn, $mi, $in, $wi);

Then iterate over it using foreach , or index it using $i .

Your code is vulnerable to SQL injection attacks. 您的代码容易受到SQL注入攻击的攻击。 I strongly suggest you read up on mysqli , prepared statements etc.:

http://php.net/manual/en/book.mysqli.php

The mysql interface is officially deprecated and should not be used anymore.

How does 'mnpoints' and 'inpoints' etc... relate to "score"?If you're just looking at dumping all those values and adding them togetherm, then:

$score = $mn + $mi  + $in +  $wi;
$sql = "UPDATE ... SET score=score+$score";
function bulkUpdateSingleColumn($table, $id_column, $update_column, array &$idstovals){
    $sql = "update $table set $update_column = CASE $id_column ";
    foreach($idstovals as $id=>$val){
        $sql .= " WHEN '$id' THEN '$val' \n";
    }
    $sql .= " END
    WHERE $id_column in (" . implode(',', array_keys($idstovals)) . ")";
//debugging info
    echo '<small>'.$sql.'</small>';
    $idstovals=array();       
    db_query($sql);      
    done();       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM