foreach($results as $row){
echo "
<input type='text' name='p_name' placeholder='" . $row['p_name'] . "'>
<input type='text' name='p_description' placeholder='" . $row['p_description'] . "'>
<input type='text' name='p_price' placeholder='" . $row['p_price'] . "'>
<input type='hidden' name='product_id'>
<input type='submit' name='update' value='update'>
";
}
echo "</form>";
if(isset($_POST['update'])){
$values = [
'product_id' => $_POST['product_id'],
'p_name' => $_POST['p_name'],
];
$stmt = $pdo->prepare('UPDATE products SET p_name = :p_name WHERE
product_id = :product_id'
);
unset($_POST['update']);
foreach($values as $row){
$stmt->execute($row);
}
}
I'm trying to update multiple fields inside a database so when I update the product name for one of them, I want it to then be sent to the database. However it won't submit that specific row with the ID and instead skips to the the last one and insert blank data. How am I able to pick which specific product name i want to update? So basically updating the data inside a database with many rows.
Take a moment and think about what foreach($values)
is going to do. Will the result of that be valid data to pass to execute()
? If you had proper error reporting on your server, you would have your answer.
You're only running a single query, so all you need to do is:
$values = [
':product_id' => $_POST['product_id'],
':p_name' => $_POST['p_name'],
];
$stmt = $pdo->prepare('UPDATE products SET p_name = :p_name WHERE product_id = :product_id');
$stmt->execute($values);
Note you need to include the colon in the parameter array index if you're using named parameters.