Php array, how to dynamically insert data into mysql table if field names are unknown beforehand?

I get some data in an array that will be stored in a mysql table. The table field names are the same as keyin the key / value pair in the array, however I do not know in advance which key / value pairs will come

// First execution
$array1 = array('a'=> 'str1', 'b'=> 'str2', 'c'=> 'str3', 'd'=> 'str4');

// second execution
$array2 = array('a'=> 'str6', 'c'=> 'str7', 'e'=> 'str5');

// third execution
$array3 = array('b'=> 'str8', 'd'=> 'str9', 'e'=> 'str10');

Thus, the above indicates the way in which data can flow. Below is an example db table structure

column 1 name = id (auto increment)
column 2 name = 'a'
column 3 name = 'b'
column 4 name = 'c'
column 5 name = 'd'
column 6 name = 'e'
column 7 name = 'f'

Please note that there may be some unexpected data, but if the db field (column) does not exist for this unexpected value, the data should be skipped. I just need to insert data in which a column exists for it, and any non-existent values ​​must be zero for the column. Hope this makes sense to someone.

SQL php?

+3
2

. - :

$keys = array_keys($arr);
$vals = array();
foreach ($keys as $k)
{
    $vals[] = "'".mysql_real_escape_string($arr[$k])."'";
}
$qry = "INSERT into tab1 (".implode(',', $keys).") VALUES (".implode(',', $vals).")";

, . , GordonM DESCRIBE TABLES - , , , $keys ( , , array_intersect())

+1

Zend_Db_Table, Zend Framework. http://framework.zend.com/manual/en/zend.db.table.html , , . Zend_Db_Table , . .

:

$db = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host'     => 'localhost',
    'username' => 'test',
    'password' => 'test',
    'dbname'   => 'test'
));
Zend_Db_Table::setDefaultAdapter($db);
$table = new Zend_Db_Table('table_name');    
$info = $table->info();

// assuming array1 contains keys => values    
$arr = array_intersect_key($array1,array_flip($info['cols']));    
$table->insert($arr);
0

All Articles