代码更新的
我有一个名为ans_1、ans_2、ans_3查询字符串编号为2或3的表,根据管理员要保存的答案,所以它们看起来像这个?1=aaa&2=bbb或?1=aaa&2=bbb&3=ccc,我的重点是保存列中的每个查询字符串,所以我使用下面的代码,但它只使用查询字符串的最后一个值。
$queries = $_SERVER['QUERY_STRING'];
$answers = explode("&",$queries );
$num = count($answers);
foreach($answers as $val){
$chars= strlen($val);
$test = substr($val,2,$chars-2);
for($x=1; $x<=$num; $x++){
$Q = "update vote set ans_'$x' = '$test' where Vote_ID = '1'";
$R = mysql_query($Q);
if($R) { echo "done"; } else { echo mysql_errno(); }
}
}发布于 2012-02-21 16:13:53
如果您有要替换$x的动态列,请不要将$x括在引号中:
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";请确保用$_SERVER['QUERY_STRING']转义mysql_real_escape_string()的内容。
$test = mysql_real_escape_string($test);在PHP中解析查询字符串的正确方法是使用parse_str(),而不是尝试在&上使用explode()。
$queryvars = array();
$parse_str($_SERVER['QUERY_STRING'], $queryvars);
foreach ($queryvars as $key=>$value) {
// do the loop
}但是,既然您正在抓取整个查询字符串,而不过滤任何特定变量,那么为什么不直接使用$_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++;
}更新
为了帮助您理解为什么您的代码不能工作,我将在这里修改它。但是,这不是执行此任务的首选方法。如上所述,使用foreach($_GET)要好得多。正确地缩进循环将有助于发现问题:
$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...
}发布于 2012-02-21 16:13:15
你需要删除单引号。尝试:
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";发布于 2012-02-21 16:13:39
如果要获取查询的值,则删除variable..may周围的引号,希望使用mysql_real_escape_string。
$Q = "update vote set `ans_$x` = '" . mysql_real_escape_string($test) . "' where Vote_ID = '1'";https://stackoverflow.com/questions/9380920
复制相似问题