在while循环中创建变量并使用循环

时间:2012-11-02 14:16:39

标签: string variables while-loop comma

我想使用在其外部的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;

1 个答案:

答案 0 :(得分: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);