php - 使用内爆将 HTML 表单 $_POST 数组插入 MySQL

标签 php mysql html arrays implode

我有以下 html 提交表单。此表单是一个 PHP_SELF 并将输入数据作为数组存储在 $_POST 中。

<html>
<body>
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Direct Bill Information:</legend>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" />
</fieldset>
<input type="submit" value="submit" name="submit" />
</form>
</body>
</html>

我有一个 MySQL 表,其中包含字段“db_num”和“db_amnt”,我想将数组中的所有输入数据插入到表中。我环顾四周,“内爆”似乎是最好的方法,但经过大量研究后,我仍然无法让它发挥作用。整个 PHP 执行并没有错误地完成,但是,它没有显示两列的所有 10 行,而是只显示两列的 2 行,所有条目的值都为 0。这是我正在使用的代码:

$sql2 = array();
foreach($_POST as key=>$value)
{
    if(key != 'submit')
    {   
        if($value != '')
        {   
            $sql2[] = '("'.mysql_real_escape_string($value['db_num']).'", "'.$value['db_amnt'].'")';
        }   
    }
}
mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',', $sql2)); 

我做了一些调试并在 foreach 循环中回显了 $value,结果发现它只显示了三个术语; “阵列”、“阵列”和“提交”。进一步检查表明,我可以从提交表单中获取要显示的值的唯一方法是通过 $_POST[db_num] 和 $_POST[db_amnt] 而不是仅通过 $_POST 执行 foreach 循环。我不太确定为什么要这样做以及如何解决它。这是我在 PHP 中的第一个代码,我边学边学。我真的很感激我能得到的任何帮助!

最佳答案

试试这个

$db_num = $_POST['db_num'];
$db_amnt = $_POST['db_amnt'];

$items = array_combine($db_num,$db_amnt);

$pairs = array();

foreach($items as $key=>$value){
  $pairs[] = '('.intval($key).','.intval($value).')';
}

mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',',$pairs));

关于php - 使用内爆将 HTML 表单 $_POST 数组插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11720981/

相关文章:

MYSQL if语句问题

javascript - 中文 SpeechSynthesis API -- Firefox

PHP print_r 有效,但 json_encode 返回空

php - 如何在 dockerized Wordpress 上启用 LDAP?

mysql - Rails + MySQL 统一码

mysql - 对此可以优化的查询是什么?

Javascript如何使函数在其他函数上工作

javascript - Html 密码框,如果正确,淡入显示博客

php - 如何从 Iframe 获取父页面信息并使用该信息在 Iframe 中显示 PHP 页面

php - 多选字段 - 多次使用选定的 ="selected"