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条)

报告相同问题?