gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:33 26 4
gpt4 key购买 nike

所以我正在制作一个 php 文件,将多行更新到 mysql,但是每当我提交时我都会遇到问题,而且我不知道我是否很好地使用了 foreach。这是我的代码:

$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);
}

}

错误显示“ undefined offset :2”我是这里的新手,这是我第一次使用数组。希望有人能帮忙。请!

最佳答案

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

附言您的代码容易受到 SQL 注入(inject)攻击

关于PHP - 如何使用 foreach 更新多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42132332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com