Php,Mysql插入动态查询

时间:2016-05-17 14:18:10

标签: php mysql

我有一个这样的数组:

stdClass Object
(
    [id] => 1
    [name] => John
    [email] => lcook0@mail.co.uk
    [website] => google.com
    [phone] => 0-(343)926-3114
    [address] => 620 Main Center
    [city] => Fukushima-shi
    [country] => JP
    [zip] => 
    [vat] => 123456
    [status] => 1
    [created] => 2016-03-10 15:56:44
)

但我不知道键和值,因为每个数组都不同。我需要的是将数组插入数据库。类似的东西:

$keys = '';
$values = '';
foreach ($array as $key => $value) {
    $keys .= implode(",", $key);
    $values .= implode(",", $value);
}
"INSERT INTO `users` ($keys) VALUES ($values);"

我的例子不起作用,因为implode需要一个数组

2 个答案:

答案 0 :(得分:0)

考虑使用替代插入格式:INSERT INTO tbl SET x=1, y=2...

这也是准备好的查询的绝佳机会:

$mapped = array_map(function($k) {return "`".$k."` = ?";},array_keys($array));
$stmt = $dbconnection->prepare("INSERT INTO `users` SET ".implode(", ",$mapped);
$stmt->execute(array_values($array));

确切的代码,包括如何传递参数值,会有所不同,但上面的样式是PDO-ish。在您的示例中,您最终得到:

INSERT INTO `users` SET `id` = ?, `name` = ? ...

1John ...将被正确发送。

答案 1 :(得分:0)

您的代码中的问题是您正在破坏字符串而不是数组。以这种方式做到:

foreach ($obj as $key => $value) {
    $keys[] = "`$key`";
    $values[] = "'$value'";
}

$keys = implode(",", $keys);
$values = implode(",", $values);

$sql = "INSERT INTO `users` ($keys) VALUES ($values);";