本质上,我正在尝试使用从名为“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:   </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.' </td>';
}
$my_s->close(); $my->close();?>
</tr>
</table>
最佳答案
您可以使用 foreach
循环来更新 $_POST['unit']
中的每个徽章编号。或者,您可以使用它来构造要在 IN
测试中使用的值列表。不幸的是,您不能将参数绑定(bind)到此,因此有必要明确地转义它们。
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);
}
关于php - mysql 从 $_POST 数组更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21586281/