ronquiq
ronquiq

Reputation: 2717

Loop textfield value and submit to database

$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.'');
}

course table

userid    score
 4         45%
 3          30%
 5          80%

It wasn't updating to table. And I tried to echo the variables, It was showing only the last row, but I edited for user 3 Can anyone suggest where I went wrong

Upvotes: 0

Views: 305

Answers (1)

Waygood
Waygood

Reputation: 2693

Your reusing the same input, so it will only submit the last one

change

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

to

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);
    }
  }
}

Upvotes: 1

Related Questions