Update echoed data using WHILE loop. Only updates

2019-09-05 08:40发布

问题:

I can't seem to be able to update any records except the first one. I am not sure how to modify any of the displayed records.

<?php

    if(isset($_POST["action"]) == "update")
    {
        $id = $_POST['m_id'][0];
        $type = $_POST['type'][0];
        // if I echo $id & $type, it only gives me the first record.**
        mysql_query("
          UPDATE membership_type
          SET mt_type ='$type'
          WHERE mt_id = '$id'"
        );
    } 

    ?>

ALl of this is within the same php page.

<form name=form action='' method='post'>

  <?php 
  $result=mysql_query("SELECT * FROM membership_type;");
  while($rows=mysql_fetch_array($result))
  {  ?>
    <input size=35 class=textField type=text name='type[]' value='<?php echo  $rows['mt_type']; ?>'>
    <input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
    <input type=submit value="Update">
  <?php 
  } 
  ?>

How do I edit any of the displayed records by simply clicking Update button???

回答1:

First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:

<?php  

// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');

// Check if there's POST request in this file
if($_POST){ 

    foreach($_POST['m_id'] as $id => $type){
      $query = "UPDATE membership_type
                SET mt_type = '".$type."'
                WHERE mt_id = '".$id."'";

      // Try to exec the query
      $mysqli->query($query) or die($mysqli->error);
    }
}else{ 

  // Get all membership_type records and then iterate
  $result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>

  <form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
    <?php while($row = $result->fetch_object()){ ?>
      <input size='35' 
             class='textField' 
             type='text' 
             name='m_id[<?php echo $row->mt_id ?>]' 
             value='<?php echo $row->mt_type; ?>'>
      <input type='submit' value="Update">
    <?php } ?>
  </form>

<?php } ?>

Third: In order to add more security (this code is vulnerable), try mysqli_prepare



回答2:

Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].



回答3:

Replace it. Hope this works.

<?php

    if(isset($_POST["action"]) == "update")
    {
        $id = $_POST['m_id'];
        $type = $_POST['type'];
        $i = 0;
        foreach($id as $mid) {
             mysql_query("UPDATE membership_type
                         SET mt_type='".mysql_real_escape_string($type[$i])."'
                         WHERE mt_id = '".intval($mid)."'") OR mysql_error();
        $i++;
        }
    } 

    ?>


回答4:

Try this :

if(isset($_POST["action"]) == "update")
{
        $id = $_POST['m_id'];
        $type = $_POST['type'];
        $loopcount = count($id);
        for($i=0; $i<$loopcount; $i++)
        {
          mysql_query("
           UPDATE membership_type
           SET mt_type ='$type[$i]'
           WHERE mt_id = '$id[$i]'"
          );
       }
} 


回答5:

You HTML was malformed and you were passing as an array but then only using the first element. Consider:

<form name="form" action="" method="post">

<?php 
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
    echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
    <input type="submit" value="Update">
</form>

Then the server script:

<?php

if(isset($_POST["action"]) && $_POST["action"] == "Update"){

    foreach($_POST['m_ids'] as $mt_id => $mt_type)
        mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));

} 

There are other things you could be doing here, eg. prepared statements, but this should work.