首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在db php-mysql中插入查询字符串时出错

在db php-mysql中插入查询字符串时出错
EN

Stack Overflow用户
提问于 2012-02-21 16:11:07
回答 4查看 683关注 0票数 0

代码更新的

我有一个名为ans_1、ans_2、ans_3查询字符串编号为2或3的表,根据管理员要保存的答案,所以它们看起来像这个?1=aaa&2=bbb或?1=aaa&2=bbb&3=ccc,我的重点是保存列中的每个查询字符串,所以我使用下面的代码,但它只使用查询字符串的最后一个值。

代码语言:javascript
复制
$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(); }    
    }
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-02-21 16:13:53

如果您有要替换$x的动态列,请不要将$x括在引号中:

代码语言:javascript
复制
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";

请确保用$_SERVER['QUERY_STRING']转义mysql_real_escape_string()的内容。

代码语言:javascript
复制
$test = mysql_real_escape_string($test);

在PHP中解析查询字符串的正确方法是使用parse_str(),而不是尝试在&上使用explode()

代码语言:javascript
复制
$queryvars = array();
$parse_str($_SERVER['QUERY_STRING'], $queryvars);
foreach ($queryvars as $key=>$value) {
   // do the loop
}

但是,既然您正在抓取整个查询字符串,而不过滤任何特定变量,那么为什么不直接使用$_GET呢?

代码语言:javascript
复制
$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)要好得多。正确地缩进循环将有助于发现问题:

代码语言:javascript
复制
$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...
}
票数 2
EN

Stack Overflow用户

发布于 2012-02-21 16:13:15

你需要删除单引号。尝试:

代码语言:javascript
复制
$Q = "update vote set ans_$x = '$test' where Vote_ID = '1'";
票数 1
EN

Stack Overflow用户

发布于 2012-02-21 16:13:39

如果要获取查询的值,则删除variable..may周围的引号,希望使用mysql_real_escape_string

代码语言:javascript
复制
$Q = "update vote set `ans_$x` = '" . mysql_real_escape_string($test) . "' where Vote_ID = '1'";
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9380920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档