mysql从$ _POST数组更新多行

时间:2014-02-05 19:07:45

标签: php mysql arrays variables post

基本上我试图使用我从名为“units”的$_POST变量获得的数组来更新多个MySQL行。被困在试图弄明白这一点。这就是我到目前为止所做的:

当前代码没有添加到第二人:

if(isset($_POST['unit'])){ $units .= implode(', ', $_POST['unit']); } else { redirect('addcall.php?err=7'); } 

$my_s = $my->prepare('INSERT INTO `calls`(`call_taker`, `call_time`, `call_type`, `call_priority`, `call_location`, `call_city`, `reporter_name`, `reporter_num`, `call_info`, `units`) VALUES (?,?,?,?,?,?,?,?,?,?)') or die($my->error);
$my_s->bind_param('sssisssiss', $name, $date, $c_type, $c_prio, $c_loc, $c_city, $r_name, $r_num, $c_info, $units) or die($my->error);
$my_s->execute() or die($my->error);
$my_s->close();
$my->close();
$my = new mysqli(HOST, USER, PASS, DB);
$my_s2 = $my->prepare('UPDATE `users` SET `busy` = 1 WHERE `badge` = ? AND `enabled` = 1 AND `confirmed` = 1 AND `duty` = 1') or die($my->error);
$my_s2->bind_param('s', $units) or die($my-error);
$my_s2->execute() or die($my-error);
$my_s2->close();
$my->close();
redirect('dashboard.php');

        <table> // table for checkboxes thats in main HTML area
        <tr> <td>Units Available:&nbsp&nbsp&nbsp</td>
        <?php
        $my = new mysqli(HOST, USER, PASS, DB);
        $my_s = $my->prepare('SELECT `name`, `badge` FROM `users` WHERE `duty` = 1 AND `busy` = 0');
        $my_s->execute();
        $my_s->store_result();
        if($my_s->num_rows == 0){
            echo "<td>None</td>";
        }
        $my_s->bind_result($u_name, $u_badge);
        while($row = $my_s->fetch()){
            echo '<td><input type="checkbox" name="unit[]" value="'.$u_badge.'">'.$u_name.' , #'.$u_badge.'&nbsp</td>'; 
        }
        $my_s->close(); $my->close();?>
        </tr>
        </table>

2 个答案:

答案 0 :(得分:0)

我认为您的HTML代码缺少“表单”标记。 html中的每种类型的“输入”都需要在“form”和“/ form”标记内,这些标记定义了表单发送的方法(POST或GET)以及目标(什么是php文件),由“行动“参数。

答案 1 :(得分:0)

您可以使用foreach循环更新$_POST['unit']中的每个徽章编号。或者,您可以使用它来构建要在IN测试中使用的值列表。不幸的是,您无法将参数绑定到此,因此必须明确地转义它们。

if (isset($_POST['unit'])) {
    $units = implode(', ', $_POST['unit']);
    $my_s = $my->prepare('INSERT INTO `calls`(`call_taker`, `call_time`, `call_type`, `call_priority`, `call_location`, `call_city`, `reporter_name`, `reporter_num`, `call_info`, `units`) VALUES (?,?,?,?,?,?,?,?,?,?)') or die($my->error);
    $my_s->bind_param('sssisssiss', $name, $date, $c_type, $c_prio, $c_loc, $c_city, $r_name, $r_num, $c_info, $units) or die($my->error);
    $my_s->execute() or die($my->error);

    $in_units = implode(', ', array_map(function($u) use ($my) { return "'" . $my->real_escape_string($u) . "'"; }, $_POST['unit']));
    $my_s2 = $my->prepare("UPDATE `users` SET `busy` = 1 WHERE `badge` IN ($in_units) AND `enabled` = 1 AND `confirmed` = 1 AND `duty` = 1") or die($my->error);
    $my_s2->execute() or die($my-error);
}