I can't changed the value in a row inside of my DB, when I select another radio different of the checked in the update form... always returns the previous state... How can I make it works?
Here are the captures:
But when I refresh the window, the checked input is always the previous one.
Here is the code:
//form:
.....
<td>
<input type="text" value="<?php echo $venta; ?>" name="venta[]" id="venta_<?php echo $i; ?>" class="form-control" autocomplete="off" placeholder="Precio de venta" required="required"/>
</td>
<td>
<input type="radio" name="principal[]" id="principal_<?php echo $i; ?>" <?php if($principal == 1){ echo 'value="0" checked="checked"';} else { echo 'value="1"';}; ?>>
</td>
.....
</tr>
//the insert/update code:
$sql = "INSERT INTO MEDIDAS (idMed, principal, cod, presentacion, cantidad, compra, venta, id_user)
VALUES ";
$insertQuery = array();
$insertData = array();
foreach ($_POST['venta'] as $i => $venta) {
$insertQuery[] = '(?, ?, ?, ?, ?, ?, ?, ?)';
$insertData[] = $_POST['idMed'][$i] == '' ? null : $_POST['idMed'][$i];
$insertData[] = $_POST['principal'][$i] == '' ? 0 : $_POST['principal'][$i]; //this is the row with the input radio
$insertData[] = $code;
$insertData[] = $_POST['presentacion'][$i];
$insertData[] = $_POST['existencia1'][$i];
$insertData[] = $_POST['compra'][$i];
$insertData[] = $_POST['venta'][$i];
$insertData[] = $id_user;
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$sql .= " ON DUPLICATE KEY UPDATE
principal = VALUES (principal), cod = VALUES (cod), presentacion = VALUES (presentacion), cantidad = VALUES (cantidad),
compra = VALUES (compra), venta = VALUES (venta), id_user = VALUES (id_user)
";
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
Only the checked radio button is sent to the server. So you don't get a parameter for each row, there's just one value for the entire form. So it shouldn't use a []
name.
Instead, give each button a value with the row index.
<td>
<input type="radio" name="principal" id="principal_<?php echo $i; ?>" value="<?php echo $i; ?>" <?php if($principal == 1){ echo 'checked="checked"';} ?>>
</td>
Then in your loop when processing the form you can check whether the value of the radio button matches the index of the loop.
foreach ($_POST['venta'] as $i => $venta) {
$insertQuery[] = '(?, ?, ?, ?, ?, ?, ?, ?)';
$insertData[] = $_POST['idMed'][$i] == '' ? null : $_POST['idMed'][$i];
$insertData[] = $_POST['principal'] == $i ? 1 : 0;
$insertData[] = $code;
$insertData[] = $_POST['presentacion'][$i];
$insertData[] = $_POST['existencia1'][$i];
$insertData[] = $_POST['compra'][$i];
$insertData[] = $_POST['venta'][$i];
$insertData[] = $id_user;
}