简体   繁体   English

php,mysql插入动态查询

[英]Php, Mysql insert dynamic query

I have an array like this: 我有一个像这样的数组:

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
)

but I will not know the keys and values, since each array will be different. 但我不会知道键和值,因为每个数组都不同。 What I need is to insert array into database. 我需要的是将数组插入数据库。 Something like: 就像是:

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

My example does not work, since implode requires an array 我的示例不起作用,因为内爆需要一个数组

Consider using the alternative insert format: INSERT INTO tbl SET x=1, y=2... 考虑使用其他插入格式: INSERT INTO tbl SET x=1, y=2...

This is also a great opportunity for prepared queries: 这也是准备查询的绝佳机会:

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

The exact code, including how to pass the parameter values, will vary but the above is PDO-ish in style. 确切的代码(包括如何传递参数值)会有所不同,但以上内容是PDO式的。 In your example, you'd end up with: 在您的示例中,您将得到:

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

And the values 1 , John ... would be sent appropriately. 并且值1John ...将被适当地发送。

The problem in your code is that you are imploding a string rather than an array. 您的代码中的问题是您要插入字符串而不是数组。 Do it in this manner: 以这种方式执行:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM