code updated
我有一个名为 vote 的表,其中包含三个字段 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(); }
}
}
最佳答案
如果您有要替换为 $x
的动态列,请不要将 $x
括在引号中:
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";
请务必使用 mysql_real_escape_string()
对 $_SERVER['QUERY_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...
}
关于php - 将查询字符串插入数据库 php-mysql 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9380920/