I can fetch the data but the submit button is not working. I am confused with the update query and storing data in array. Here is the code for fetching and showing data in table.
`<?php
while ($rows=mysqli_fetch_assoc($result)){ ?>
<tr>
<td align="center">
<?php $id[]=$rows['id']; ?><?php echo $rows['id']; ?>
</td>
<td align="center">
<input name="name[]" type="text" id="name" value="<?=$rows['name']; ?>">
</td>
<td align="center">
<input name="lastname[]" type="text" id="lastname" value="<? =$rows['lastname']; ?>">
</td>
<td align="center">
<input name="email[]" type="text" id="email" value="<?=$rows['email']; ?>">
</td>
</tr>
`
Here is the code for submit button
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST["Submit"] != ""){
$count = mysqli_num_rows($result);
for($i=0;$i<$count;$i++){
$sql2="UPDATE test_mysql SET name='".$_POST["name"][$i]."',lastname='".$_POST["lastname"][$i]."', email='".$_POST["email"][$i]."' WHERE id='$id[$i]'";
$result1=mysqli_query($con, $sql2);
}
header("Location: update-multiple-2.php");
}
If you handle POST after outputting form (to set variable $id
) and variable $test_mysql
is set to existing table in your database and all columns exists and you are only one who can add or remove row (because it will change the $id
variable) then it should work.
Maybe this could help:
if(!$result1=mysqli_query($con, $sql2)){
echo 'Error: '.mysqli_error();
}
You need to debug it somehow:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST["Submit"] != ""){
$count = mysqli_num_rows($result);
$error = '';
for($i=0;$i<$count;$i++){
$sql2="UPDATE $test_mysql SET name='".$_POST["name"][$i]."',lastname='".$_POST["lastname"][$i]."', email='".$_POST["email"][$i]."' WHERE id='$id[$i]'";
if(mysqli_query($con, $sql2) === FALSE){
$error .= 'SQL query failed, SQL: '.$sql2.', Error: '.mysqli_error() . "
";
}
}
if(!$error){
header("Location: update-multiple-2.php");
}else{
echo $error;
exit();
}
}