创建一个动态的php插入到mysql函数中? [英] creating a dynamic php insert into mysql function?

查看:25
本文介绍了创建一个动态的php插入到mysql函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含很多变量的帖子,我想知道是否有某种方法可以动态地将信息插入 mysql,而不是手动输入,因为帖子变量会根据用户选择的内容而变化.

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.

推荐答案

这就是我们用来做类似事情的方法(插入到我们无法控制的表中,并且没有 API 访问权限)

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)

使用 DESCRIBE 查询可确保仅插入存在的列.

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) . ')';

DB() 是我们围绕 MDB2 的包装器.

edit: DB() is our wrapper around MDB2.

当然,这允许他们填写整行.如果您有受限制的列(自动增量 ID 等),则必须从表单数据中过滤掉这些列...

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆