将php foreach循环存储在字符串中

时间:2015-06-13 03:43:51

标签: php mysql sql arrays multidimensional-array

我们有一个数组名valArray,如下所示:

$valArray = array (
             name => 'Rahul',
             Address => 'New Delhi',
             Pass => '1234',
             class => '10th',
             School => 'DPS',
             Roll => '134567',
           )

生成dynamicaly,所以,实际上我们想要的是运行这种sql query

$query = "insert into table_name set
          foreach($valArray as $key => $value) {
            $key = "$value",
          }
         ";

和静态应该是这样的:

$query = "insert into table_name set
              name = 'Rahul',
              Address = 'New Delhi',
              Pass = '1234',
              class = '10th',
              School = 'DPS',
              Roll = '134567'
        ";

我知道这是syntactically错误,但有没有办法执行此类操作。

1 个答案:

答案 0 :(得分:2)

 $sql = "insert into $table(" . implode(',', array_keys($valArray)) . " values('" . implode("','", array_values($valArray)) . "')";

array_values的调用并非必要,但更好地说明了我认为的想法

编辑:引用值;他们也应该逃脱