If you have dynamic columns for which you are substituting $x, do not enclose $x in quotes:
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";
Please be sure to escape the contents of $_SERVER['QUERY_STRING'] with mysql_real_escape_string().
$test = mysql_real_escape_string($test);
The proper way to parse a query string in PHP is with parse_str(), rather than attempting to explode() on the &.
$queryvars = array();
$parse_str($_SERVER['QUERY_STRING'], $queryvars);
foreach ($queryvars as $key=>$value) {
// do the loop
}
However, since you are grabbing the whole query string, and not filtering any specific variables, why not just use $_GET?
$x = 0;
foreach ($_GET as $key=>$value) {
// do the loop...
$test = mysql_real_escape_string($value);
$Q = "update vote set ans_'$x' = '$test' where Vote_ID = '1'";
$x++;
}
Update
To help you understand why your code isn't working, I'll modify it here. However, this is not the preferred method of performing this task. Using foreach($_GET) as above is much better. Indenting the loop properly will help reveal the problem:
$queries = $_SERVER['QUERY_STRING'];
$answers = explode("&",$queries );
$num = count($answers);
// Your foreach loops over the available querystring params:
// Start by initializing $x to 0
$x = 0;
foreach($answers as $val){
$chars= strlen($val);
$test = substr($val,2,$chars-2);
// You are already inside the foreach loop, so
// you don't want to start another loop which uses the same value for $test
// on each iteration. Instead $x was set to 0 before the outer foreach...
// There is no need for an inner loop.
//for($x=1; $x<=$num; $x++){
// On first iter here, $x is 0. Increments at the end of the loop iter.
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";
$R = mysql_query($Q);
if($R) {
echo "done";
} else {
echo mysql_errno();
}
// On each iteration, increment $x here.
$x++;
//} // the inner for loop, commented out...
}