创建一个动态php插入到mysql函数? [英] creating a dynamic php insert into mysql function?
问题描述
这是我们用来做类似的事情(插入到我们无法控制的表中,没有API访问)
使用DESCRIBE查询确保仅插入存在的列。
$ db = new DB();
$ sql ='DESCRIBE`table`';
$ result = $ db-> query($ sql);
$ row = array();
$ query = array();
while($ row = $ result-> fetchRow())
{
if(array_key_exists($ row ['field'],$ form_data))
if(is_null($ form_data [$ row ['field']]))
$ query [$ row ['field']] ='NULL';
else
$ query [$ row ['field']] = $ db-> quote($ form_data [$ row ['field']]);
}
$ keys = array_keys($ query);
foreach($ keys as& $ key)
$ key = $ db-> quoteIdentifier($ key);
unset($ key);
$ vals = array_values($ query);
$ sql ='INSERT INTO'table`'
。 '('。implode(',',$ keys)''''
。 'VALUES('。implode(',',$ vals)'''';
编辑:DB()是我们在MDB2周围的包装。
当然这可以让他们填写整行。如果您有限制列(自动增量ids等),则必须对表单数据进行过滤...
i have a post with a LOT of variables, and I was wondering if there was some way of inserting the information into mysql dynamically, rather than typing it all out manually, as the post variables change depending on what the user selects.
This is what we use to do a similar thing (inserting into a table we have no control over, and which has no API access)
Using the DESCRIBE query ensures only columns that exist are inserted.
$db = new DB();
$sql = 'DESCRIBE `table`';
$result = $db->query($sql);
$row = array();
$query = array();
while ($row = $result->fetchRow())
{
if (array_key_exists($row['field'], $form_data))
if (is_null($form_data[$row['field']]))
$query[$row['field']] = 'NULL';
else
$query[$row['field']] = $db->quote($form_data[$row['field']]);
}
$keys = array_keys($query);
foreach ($keys as &$key)
$key = $db->quoteIdentifier($key);
unset($key);
$vals = array_values($query);
$sql = 'INSERT INTO `table` '
. '(' . implode(', ', $keys) . ') '
. 'VALUES(' . implode(', ', $vals) . ')';
edit: DB() is our wrapper around MDB2.
And of course this allows them to fill in the entire row. If you have restricted columns (auto-increment ids and such), you'll have to filter those out of the form data...
这篇关于创建一个动态php插入到mysql函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!