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

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

问题描述

我有一个有大量变量的帖子,我想知道是否有一些方法可以动态地将信息插入到mysql中,而不是手动输入信息,因为后置变量根据用户选择而变化。

解决方案

这是我们用来做类似的事情(插入到我们无法控制的表中,没有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屋!

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