0

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

Alko
  • 1,421
  • 5
  • 25
  • 51

2 Answers2

0

Consider using the alternative insert format: 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. In your example, you'd end up with:

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

And the values 1, John ... would be sent appropriately.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

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);";
CodeGodie
  • 12,116
  • 6
  • 37
  • 66