duanhua5523 2017-02-09 09:08
浏览 122
已采纳

PHP - 如何使用foreach更新多行?

so i'm making a php file that updates multiple rows to mysql but I'm having a problem whenever i submit,and I have no idea if I'm using foreach well. here is my code:

$query = "SELECT id, departments, deptName, headOfOffice FROM aip";
$result = mysqli_query($db,$query);
$count = mysqli_num_rows($result);

while ($row = mysqli_fetch_assoc($result)) {

        echo '<tr>';
        echo '<td><input type="text" name="id[]" value="'.$row['id'].'" readonly></td>';
        echo '<td><input type="text" id ="department_code" name="department_code[]" value="'.$row['departments'].'"></td>';
        echo '<td><input type="text" id="department_name" name="department_name[]" value="'.$row['deptName'].'"></td>';
        echo '<td><input type="text" id="department_head" name="department_head[]" value="'.$row['headOfOffice'].'"></td>';
        echo '</tr>';

}

echo '<tr>';
echo '<td></td>';
echo '<td></td>';
echo '<td><input type="submit" name="update" value="Update">';
echo '</tr>';



if($_SERVER["REQUEST_METHOD"] == "POST"){

$deptid = $_POST['id'];
$code = $_POST['department_code'];
$dname = $_POST['department_name'];
$dhead =$_POST['department_head'];

foreach($_POST['id'] as $count){ \\ i don't know if this is right.

$query2 = "UPDATE aip SET deparments = '".$code[$count].'" WHERE id = "'.$deptid[$count]."'";
$result2 = mysqli_query($db,$query2);
}

 }

the error says "Undefined offset: 2" I'm a newbie here, and this is my first time using arrays. hope someone could help. please!

  • 写回答

3条回答 默认 最新

  • dpb75177 2017-02-09 09:15
    关注
    foreach($_POST['id'] as $count => $id){
        $query2 = "UPDATE aip SET deparments = '".$code[$count]."' WHERE id = '".$deptid[$count]."'";
        $result2 = mysqli_query($db,$query2);
    }
    

    P.S. your code is vulnerable to SQL injection

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题