【发布时间】:2013-02-22 05:04:58
【问题描述】:
我正在尝试使用 php 将复选框的选定值插入到 mysql 数据库中。我只是不明白为什么它不起作用,因为它可以很好地回显所有值,但它只会将第一个选择的值插入到数据库中。
HTML:
<b>Injury type:</b>
Bruise <input type='checkbox' name='InjuryType[]' value='1'><br>
Cut <input type='checkbox' name='InjuryType[]' value='2'><br>
Graze <input type='checkbox' name='InjuryType[]' value='3'><br>
Break <input type='checkbox' name='InjuryType[]' value='4'><br>
Bump <input type='checkbox' name='InjuryType[]' value='5'><br>
PHP:
foreach($_POST['InjuryType'] as $value) {
$insert = mysql_query("INSERT INTO AccidentInjuryLink(InjuryID) VALUES ('$value')");
echo $value;
}
【问题讨论】:
-
print_r($_POST);是您期望的数据吗? -
1.不要使用 mysql 驱动程序,而是使用 PDO。这可以防止 SQL 注入;我还可以看到您没有逃避发布的值。 2. 也许该列有一个主索引,这意味着所有数字必须是唯一的,因此只插入第一个值。
-
Please, don't use
mysql_*functions in new code。它们不再维护and are officially deprecated。看到red box?改为了解prepared statements,并使用PDO 或MySQLi - this article 将帮助您决定哪个。如果您选择 PDO,here is a good tutorial。 (另外,就像 Silkfire 说的,你在这里也很容易受到 SQL injection 的攻击。) -
您的代码容易受到 SQL 注入攻击,here 简要概述了它们是什么以及如何防止它们。
-
停止使用 mysql_* 停止'垃圾邮件'
标签: php mysql forms foreach checkbox