tags:

views:

34

answers:

2

Hello,

Im sorting a list and using ajax to update a database. I need help parsing the string, this is the query string that i need to parse:

images_list[]=32&images_list[]=95&images_list[]=97&images_list[]=96&images_list[]=102&images_list[]=103&images_list[]=99&images_list[]=101&images_list[]=98&john=hi

I have put john=hi to test to see if the string is actually being sent via ajax to the processor.php file. I am able to get the variable john=hi from the url, so the query string is being sent perfectly fine. This is my code so far, but i can't seem to access the data i need, it appears as if nothing is there:

<?php
//Connect to DB
require_once('connect.php');

parse_str($_GET['images_list']);
for ($i = 0; $i < count($images_list); $i++) { 
    $id = $images_list[$i]; 
    mysql_query("UPDATE images SET ranking = '$i' WHERE id = '$id'"); 
    echo $images_list[$i]; 
} 
?>
+1  A: 

$_GET['images_list'] is an array of integers. There's nothing to parse there, PHP already did for use. So, skip the parse_str part and easily use $_GET['images_list'] instead of $images_list.

Whole code:

<?php
//Connect to DB
require_once('connect.php');

foreach ($_GET['images_list'] as $i => $id) { 
    mysql_query("UPDATE images SET ranking = ".mysql_real_escape_string($i)." WHERE id = ".mysql_real_escape_string($id)); 
    echo $id; 
}
?>
nikic
A: 

Why are you using parse_str()? $_GET['images_list'] should contain an array not a string.

Your code should be:

<?php
//Connect to DB
require_once('connect.php');

for ($_GET['images_list'] as $i=>$id) { 
    mysql_query("UPDATE images SET ranking = '".mysql_real_escape_string($i)."' WHERE id = '".mysql_real_escape_string($id)."'"); 
    echo $id; 
} 
?>

Also watch out for SQL injection! I've used mysql_escape_string() to fix that.

Christian Sciberras
mysql_escape_string is deprecated (http://php.net/manual/en/function.mysql-escape-string.php)
Anax
Sorry, meant mysql_real_escape_string - fixed. Why did I get a -1? At least, I did advise before someone followed suit...
Christian Sciberras