0

我有一张表格,可以打印出我表格中的所有用户。每个用户旁边是一个选择框和一个更新按钮。我遇到的问题是脚本只从最后一个选择框读取。如何使选择框动态化,以便脚本知道选择框来自哪一行?

选择框代码:

<select name="level" >
<option value="basic" SELECTED>Basic</option>
<option value="premium">Premium</option>
<option value="platinum">Platinum</option>
</select>

<button type="submit" name="update" value="<?php echo $row['id'] ?>">Update</button>

按下提交按钮时生效的另一个脚本中的代码:

if ( isset( $_POST['update'] ) ) {
 //Get the ID of the account that will be updated
 $userID = $_POST['update'];
 //Get the level that the admin wishes to change to
 $level= $_POST['level'];

//Connect to the DB
mysql_connect("localhost", "xxxx", "xxxx")or die("Cannot connect to database");
mysql_select_db("xxxx")or die("Database cannot be selected or it doesnt exist");

//Updates the users access level
mysql_query("UPDATE users SET level='$level' WHERE id='$userID' ");
4

3 回答 3

0

只需查看 html,您就会覆盖您的选择框值,因为它们都具有相同的名称。

最简单的解决方案是将选择框的名称转换为数组:

<select name="level[<?php echo $row['id']; ?>]" >

不,您可以在服务器端访问它们:

$_POST['level'][$userID]

您还需要切换到 PDO / mysqli 并使用绑定变量准备语句以避免您的 sql 注入问题。

于 2012-11-28T14:44:52.317 回答
0

您可以为此使用 jquery。试试这个,

 $(document).ready(function(){
  var values = [];
  $('select[name=level]').each(function() {
    values[] = $(this).val(); 
  });

  $('button[name=update]').val(values);

 });

它只读取最后一行的原因是它只$row['id']包含迭代结果集中的最后一行。

于 2012-11-28T14:46:40.290 回答
0

用这个:

<input type="hidden" name="userid[]" value="#THEUSERID"/>
<select name="level[]" >
<option value="basic" SELECTED>Basic</option>
<option value="premium">Premium</option>
<option value="platinum">Platinum</option>
</select>

if ( isset( $_POST['update'] ) ) {
    foreach($_POST['userid'] as $k=>$userID){

 //Get the level that the admin wishes to change to
        $level= $_POST['level'][$k];

//Connect to the DB
        mysql_connect("localhost", "xxxx", "xxxx")or die("Cannot connect to database");
        mysql_select_db("xxxx")or die("Database cannot be selected or it doesnt exist");

//Updates the users access level
        mysql_query("UPDATE users SET level='$level' WHERE id='$userID' ");
    }
}
于 2012-11-28T14:47:02.503 回答