Reputation: 21
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!
Upvotes: 0
Views: 4475
Reputation: 176
i have changed in your script..pls used my script. you do not need to changes any thing just copy and paste my script.
if($_SERVER["REQUEST_METHOD"] == "POST"){
$data = $_POST;
if(count($data['id'])>0){
foreach($data as $key=>$item){
$query2 = "UPDATE aip SET deparments = '".$item['department_code'][$key]."', deptName = '".$item['department_name'][$key]."',headOfOffice = '".$item['department_head'][$key]."' WHERE id = '".$item['id'][$key]."'";
$result2 = mysqli_query($db,$query2);
}
}
}
Upvotes: 0
Reputation: 11340
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
Upvotes: 3
Reputation: 524
There are two ways of using foreach:
foreach($array as $key => $value){
...
}
or
foreach($array as $value){
...
}
The foreach loop will then iterate through all elements in array, executing the code in brackets for each element once, holding the key name and the value of the element in $key
and $value
respectively (you can use other than $value
and $key
as well).
I don't fully understand what exactly you are doing in your code, so if you add an explanation, I will be able to solve your particular case;
Upvotes: 0