php - update database rows by $_POST data with key as id for row


I have the following $_POST data received from the user

url[3] = "beheer"
name[3] = "knowledge"
parent_id[3] = "0"

url[4] = "asd"
name[4] = "adasdas"
parent_id[4] = "0"

url[5] = "asdasd"
name[5] = "asdsadasd"
parent_id[5] = "0"

Where the key is the id for each data. I want to loop through all the data and update the rows

this will execute for example:

mysql_query("UPDATE table SET url = 'beheer', name = 'knowledge', parent_id='0' WHERE id = 3");

How can I solve this?




You can do that :

   foreach ($url as $key => $value)
    mysql_query("UPDATE table SET url = '$value', name = '$name[$key]', parent_id='$parent_id[$key]' WHERE id = '$key'");



As I see it, the easiest way to solve it would be to use an associative array instead. So you have one variable, called $values, and then add your names to that like this:




This will enable you to iterate over the array using a foreach loop like so.

foreach($values AS $value) {
  $url = $value['url'];
  $name = $value['name'];
  $parent_id = $value['parent_id'];

  $query = "INSERT INTO table (url,name,parent_id) VALUES ('$url','$name','$parent_id')";


This is of course a simple example, but it should help.

People are also looking for solutions to the problem: php - How to prevent "confirm form resubmission" popup after failed form submission


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.