0
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.

2
  • You don't set value to hidden product_id input Commented Dec 28, 2018 at 21:37
  • And why there is a } before </form>? What are you NOT showing us? Commented Dec 28, 2018 at 21:55

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand that however if I wanted to update multiple product names, its confusing me to a degree
Check the duplicate
0

You need to add a value to the input:

<input type='hidden' name='product_id' value="SOME VALUE">

The value may be value='" . $row['product_id'] . "', but you need to get the data somewhere, like from the database you are querying to mount the form.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.