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

388

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?

540

Answer

Solution:

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'");
993

Answer

Solution:

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:

$values[0]['url']
$values[0]['name']
$values[0]['parent_id']

$values[1]['url']
$values[1]['name']
$values[1]['parent_id']

$values[2]['url']
$values[2]['name']
$values[2]['parent_id']

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')";
}

$sql->query($query);

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

Source

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.