我有
<form action="entry.php" method="post" >
<table>
<tr>
<td>
<input type="text" name="searchid[]" id="searchid" placeholder="Data 1" ><br />
<input type="text" name="searchid[]" id="searchid" placeholder="Data 2" ><br />
<input type="text" name="searchid[]" id="searchid" placeholder="Data 3" ><br />
<input type="text" name="searchid[]" id="searchid" placeholder="Data 4" ><br />
</td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit" value="submit" /></td>
</tr>
</table>
</form>
和entry.php代码,
<?php
include "db.php";
if (isset($_POST["submit"]))
$data1 = mysql_real_escape_string($_POST['searchid']);
$query1 = "INSERT INTO php_test (name) VALUES ('$data1')";
$query = mysql_query($query1,$connection);
if($query){
header ("location: index.php");
}
else{
echo "Something Wrong";
}
?>
此代码使用单个输入数据,但是, 我想在同一列的单独字段中输入四个数据,当我提交时,它会在单独的行中插入数据,字段名称相同并且
答案 0 :(得分:3)
$_POST['searchid']
是一个数组,而不是一个字符串。你需要循环它们:
if (isset($_POST["submit"]))
foreach ($_POST['searchid'] as $searchid) {
$data1 = mysql_real_escape_string($searchid);
mysql_query("INSERT INTO php_test (name) VALUES ('$data1')") or die(mysql_error());
}
}
header("location: index.php");
此外,摆脱HTML中的重复id="searchid"
属性。 ID必须是唯一的。您可能根本不需要这些元素。
如果您有多列,可以这样做:
if (isset($_POST["submit"]))
foreach ($_POST['searchid'] as $index => $searchid) {
$data1 = mysql_real_escape_string($searchid);
$data2 = mysql_real_escape_string($_POST['searchid2'][$index]);
mysql_query("INSERT INTO php_test (name, name2) VALUES ('$data1', '$data2')") or die(mysql_error());
}
}
答案 1 :(得分:2)
当你在数组中获得价值时。所以你应该把你的insert语句放在循环中。可能是这样的: -
根据建议你不能mysql_real_escape_string
超过数组。因此,您应该从循环内部的顶部和mysql_real_escape_string
中删除每个值。
$data1 = $_POST['searchid'];
foreach($data1 as $postValues) {
$name = mysql_real_escape_string($postValues);
$query1 = "INSERT INTO php_test (name) VALUES ('$name')";
$query = mysql_query($query1,$connection);
}
答案 2 :(得分:1)
请尝试以下代码:
<?php
include "db.php";
if (isset($_POST["submit"]))
foreach($_POST['searchid'] as $id){
$searchid= mysql_real_escape_string($id);
$query1 = "INSERT INTO php_test (name) VALUES ('$searchid')";
$query = mysql_query($query1,$connection);
}
if($query){
header ("location: index.php");
}
else{
echo "Something Wrong";
}
&GT;
答案 3 :(得分:1)
试试这个:
<?php
include "db.php";
if (isset($_POST["submit"]))
foreach($_POST["submit"] as $searchval) {
$query1 = "INSERT INTO php_test (name) VALUES ('$searchval')";
$query = mysql_query($query1,$connection);
}
if($query){
header ("location: index.php");
}
else{
echo "Something Wrong";
}
?>