我有一个只有“值”文本字段的 HTML 表单。但是用户可以为 1 个提交按钮生成任意数量的“值”测试字段。这是我的 table
CREATE TABLE IF NOT EXISTS `insert` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`insert_operation` int(11) NOT NULL,
`value` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
现在,如果用户生成 4 个“值”文本字段并输入 4 个值 数据(a、b、c、d),它应该执行 4 个插入查询,但 insert_operation跟踪每次提交按钮的点击。
它看起来像下面
Id Insert_operation value 1 1 a 2 1 b 3 1 c 4 1 d 5 2 x 6 2 a
我的 html 表单有名称为值的值文本字段和名称为保存的提交按钮。
我不确定我的 PHP 代码。 我知道插入查询必须在 PHP 循环内。但是我该如何表现呢?
最佳答案
假设您的 value
字段都被命名为相同的即。 <input name="value[]" ... />
尝试这样的事情-
for($i=0;$i<count($_POST['value']);$i++){
$value = mysql_real_escape_string($_POST['value'][$i]);
if($i == 0){ // if the first increase MAX(insert_operation) by 1
mysql_query("INSERT INTO `insert` SELECT null, IFNULL((SELECT MAX(insert_operation)+1 from `insert`), 1), '{$value}'");
}
else { // if not the first use MAX(insert_operation)
mysql_query("INSERT INTO `insert` SELECT null, IFNULL((SELECT MAX(insert_operation) from `insert`), 1), '{$value}'");
}
}
第一个将获得 MAX(insert_operation)
已经在表中,如果为 null 将其设置为 1,否则它将增加 1。所有其余的将只设置 insert_operation
至 MAX(insert_operation)
.
请参阅此 SqlFiddle 示例 - http://sqlfiddle.com/#!2/afdc0/1
一些注意事项。 insert
是一个 mysql function/reserved word .重命名您的表格会更好,但至少它需要在反引号中 - `。你应该转义任何用户数据( $_POST['value']
),在这种情况下我展示了 mysql_real_escape_string()
.最后,mysql_*
功能从 php5.5 开始贬值。您应该更新到 mysqli_
或 PDO
关于php - 插入数据问题。在 php 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17520681/