0

我想使用在其外部的 while 循环中创建的变量。这是因为我想将不同的变量放在彼此之后(逗号分隔)并放入字符串变量中。之后,我将删除最后一个逗号。

这是我的代码

$result = mysql_query("SELECT * FROM ".$_POST['moduleName']);   

        while($row = mysql_fetch_array($result))
          {

          //read fieldnames from database
          $fieldName = $row['modFieldName'];

          //creating a variable with the fieldname    
          $fieldName = 'field'.$fieldName;

          //fill Variable with posted input
          $fieldName = $_POST[$row['modFieldName']];

//Put fieldname in a string (outputs: a,b,c,d,e,)
          $postString = $fieldName.","; 

        }
//Remove last comma      
$postString = substr($postString,0,-1);
         echo $postString;
4

1 回答 1

0

所以每次连接结果,而不是覆盖字符串:

    $result = mysql_query("SELECT * FROM ".$_POST['moduleName']);

    $postString = ''; 

    while($row = mysql_fetch_array($result))
    {
      //read fieldnames from database
      $fieldName = $row['modFieldName'];

      //creating a variable with the fieldname    
      $fieldName = 'field'.$fieldName;

      //fill Variable with posted input
      $fieldName = $_POST[$row['modFieldName']];

      //Put fieldname in a string (outputs: a,b,c,d,e,)
      $postString = $postString.$fieldName.","; 
    }

    //Remove last comma      
    $postString = substr($postString, 0, -1);
    echo $postString;

或者你可以使用.=. 另外,不要使用mysql_扩展——它们已经开始了弃用过程,很容易导致 SQL 注入漏洞。PDO 是一个很好的选择,如下所示。最后,绝对不要将用户提供的数据直接放入查询中!哎呀!

$query = $database->query('SELECT * FROM ' . $moduleName); # Please filter $moduleName against a list of known safe tables!

$postStrings = array_map(function($row) {
    return $_POST['field' . $row->modFieldName];
}, $query->fetchAll());

$postString = implode(',', $postStrings);
于 2012-11-02T14:22:04.303 回答