我将数组传递给查询。但是,我似乎无法添加每个值`。
Im传递的数组是:
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;
我知道我需要附上每个值,但我无法看到我需要这样做的地方。
感谢您的时间。
答案 0 :(得分:0)
尝试:
foreach ($data as $column => $value) {
$columns .= ($columns == "") ? "" : ", ";
$columns .= $column;
$values .= ($values == "") ? "" : ", ";
$values .= "'" . $value . "'";
}
答案 1 :(得分: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_keys, array_values, array_map,mysql_real_escape_string,join
出于安全原因,我使用的是mysql_real_escape_string。