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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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...