循环文本字段值并提交到数据库

时间:2012-08-01 08:12:16

标签: php

$as = mysql_query('SELECT u.id,u.username,c.score FROM user u, course c WHERE u.id = c.userid ');
echo '<form action="score.php" method="post"><table>';
while($row = mysql_fetch_array($as)
{
   $uid = $row['id'];
   $username = $row['username'];
   $score    = $row['score'];
   echo '<tr><td>'.$username.'</td>
             <td><input type="hidden" name="uid" value='.$uid.'>
                 <input type="text" name="score" value='.$score.'>
             </td>
         </tr>
}
echo '<tr><td><input type="submit" name="submit" value="update"></td></tr>';
echo '</table></form>';
if($_SERVER['REQUEST_METHOD == 'POST']
{
  $uid = $_POST['uid'];
  $score = $_POST['score'];
  $sql = mysql('UPDATE user SET c.score = '.$score.' WHERE c.userid = '.$uid.'');
}

课程表

userid    score
 4         45%
 3          30%
 5          80%

它没有更新到表格。我试图回应变量,它只显示最后一行,但我为用户3编辑了任何人都可以建议我出错的地方

1 个答案:

答案 0 :(得分:1)

您重复使用相同的输入,因此它只会提交最后一个

变化

echo '<tr><td>'.$username.'</td>
         <td><input type="hidden" name="uid" value='.$uid.'>
             <input type="text" name="score" value='.$score.'>
         </td>
     </tr>

echo '<tr><td>'.$username.'</td>
         <td><input type="hidden" name="uid['.$uid.']" value='.$uid.'>
             <input type="text" name="score['.$uid.']" value='.$score.'>
         </td>
     </tr>

ALSO

if(sizeof($_POST)>0)
{
  if(is_array($_POST['uid']))
  {
    while(list($key,$value)=each($_POST['uid'])
    {
        $sql="UPDATE user SET score='".mysql_real_escape_string($_POST['score'][$key])."' WHERE userid=".intval($value);
        mysql_query($sql);
    }
  }
}