使用对象作为数据库表定义?

时间:2016-01-02 18:38:54

标签: php mysql mass-assignment

我需要保存一个从API到我自己的数据库的对象。唯一的问题是对象有大约400个不同的领域?我真的不想整天键入它们的定义,那么有没有办法获取一个对象并将每个键转换为一个表列,然后将这些值作为插入插入?

1 个答案:

答案 0 :(得分:0)

假设对象是一维关联数组,这应该有效:

// Create a string like field1, field2, field3, ...
$column_list = implode(',', array_columns($object));
// Create placeholder string like :field1, :field2, :field3, ...
$placeholders = implode(',', array_map(function($col) {
    return ":$col";
}, array_columns($object)));
// Put them into the SQL query
$sql = "INSERT INTO tablename ($column_list) VALUES ($placeholders)";
$statement = $pdo->prepare($sql);
// The object will then be used to supply values for the placeholders
$statement->execute($object);