0

我将一个数组传递给一个查询。但是,我似乎无法添加每个值`。

我传递的数组是:

Array ( 
        [name] => Name 
        [address_1] => Address 1 
        [address_2] => Address 2 
        [address_3] => Address 3 
        [address_4] => Address 4 
        [post_code] => Post COde 
        [proptype] => rent 
        [style] => house 
        [beds] => 1 
        [bathrooms] => 1 
        [garden] => 1 
        [furnished] => yes 
        [deposit] => Deposit 
        [available] => 10/18/2013 
        [description] => Description 
      )

下面是我的代码:

    foreach ($data as $column => $value) {
            $columns .= ($columns == "") ? "" : ", ";
            $columns .= $column;
            $values .= ($values == "") ? "" : ", ";
            $values .= $value;
    }

    $sql = "INSERT INTO $table ($columns) VALUES ($values)";

    echo "--->" . $sql;
    exit;

我知道我需要包含每个值,但我看不到我需要在哪里执行此操作。

谢谢你的时间。

4

2 回答 2

0

您还可以使用一些内置的 php 函数:

// join column names with a comma
$columns = join(array_keys($data),',');

// pass every value through mysql-escape and join the values with quotes and commas
$values = join(array_map("mysql_real_escape_string",array_values($data)),'","');

// use the produced strings; make sure you wrap the values string with double quotes
$sql = "INSERT INTO $table ($columns) VALUES (\"$values\")";

供参考: array_keysarray_valuesarray_mapmysql_real_escape_stringjoin

出于安全原因,我使用 mysql_real_escape_string 。

于 2013-10-17T21:20:24.460 回答
0

尝试:

foreach ($data as $column => $value) {
    $columns .= ($columns == "") ? "" : ", ";
    $columns .= $column;
    $values .= ($values == "") ? "" : ", ";
    $values .= "'" . $value . "'";
}
于 2013-10-17T21:05:14.733 回答