使用WHILE循环更新回显的数据.仅更新一条记录 [英] Update echoed data using WHILE loop. Only updates one record

查看:77
本文介绍了使用WHILE循环更新回显的数据.仅更新一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除第一个记录外,我似乎无法更新任何记录. 我不确定如何修改任何显示的记录.

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

    ?>

所有这些都在同一php页面中.

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???

推荐答案

首先:您不应该从不使用使用 mysql _ *函数,因为它们已被弃用.
第二:尝试以下代码:

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 } ?>

第三:为了增加安全性(此代码容易受到攻击),请尝试 mysqli_prepare

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

这篇关于使用WHILE循环更新回显的数据.仅更新一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆