creating a dynamic php insert into mysql function?(创建一个动态的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函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建一个动态的php插入到mysql函数中?
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
