开发者

creating a dynamic php insert into mysql function?

i have a post with a LOT of variables, and I was wondering if there was some way of inserting the information into mys开发者_StackOverflow中文版ql 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜