August 17, 2011

Looping through post data and updating corresponding database records

Question by George Reith

I am trying to loop through some data I post through jQuery. Here is my PHP script:

<?php
include '../dbconnect.php';
$map = $_POST['map'];
$position = 0;
foreach ($map as $ID)
{
  if ($_POST['type'] == "sub") {
    $query = "UPDATE Subcategories SET `Position` = '$position' WHERE CategoryID = '$ID';";
  } else {
    $query = "UPDATE Categories SET `Position` = '$position' WHERE CategoryID = '$ID';";
  }

  $result = mysql_query($query) or die(mysql_error());
  $position ++;
}
?>

and the data it is recieving as $map is sent in this format:

ID[]=27&ID[]=28&ID[]=33&ID[]=19

Obviously my foreach is wrong, but how would I go about getting it so that I retain $maps order and each numerical value becomes the variable $ID?

Answer by Starx

Ok, Since your $map contains, ID[]=27&ID[]=28&ID[]=33&ID[]=19 string value. Do something like this

$str = str_replace($map, "ID[]=","");
$mArr = explode("&", $str);
foreach($mArr as $key) {
   //now your $key will have 27, 28, 33, 19 as the loop progresses
}

P.S. Based on the OP’s comment of $map having a string output of that

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!