根据从多选框中选择的选项的数量,我尝试将多行插入到MySQL表中。当前它正在插入一行(不管选择了多少个选项),但“strategyname”列每次都是空的。
关于如何插入多行以及为什么选项的值不会发送到表中,您有什么想法吗?
表单如下所示:
<form method="POST" action="update4.php">
<input type="hidden" name="id" value="1">
<p class="subheadsmall">Strategies</p>
<p class="sidebargrey">
<?php
$result = mysql_query("SELECT strategyname FROM sslink WHERE study_id = '{$_GET['id']}'");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategyname = $row['strategyname'];
echo $strategyname.'<br />';
}
?>
<p class="subheadsmall">Add a strategy... (hold down command key to select more than one)</p>
<select name="strategylist" multiple="multiple">
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<option value="' . $strategylist . '" >' . $strategyname . '</option>' . '\n';
}
?>
</select>
</p>
<input type="submit" class="box" id="editbutton" value="Update Article">
</form>下面是将其发送到数据库的内容:
<?php
$id=$_POST['id'];
$test=$_POST['strategylist'];
$db="database";
$link = mysql_connect("localhost", "root", "root");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
//for($i=0;$i<sizeof($_POST["test"]);$i++)
//{
//$sql = "insert into tbl_name values ($_POST["test"][$i])"; }
//sql = "INSERT INTO table_name VALUES ('" . join(",",$_POST["test"]) . "')";
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) VALUES ('$id','" . join(",",$_POST["strategylist"]) . "')")or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>发布于 2009-06-30 12:38:01
几个要点:
select需要命名为strategylist[],以便告诉PHP它将包含一个数组而不是单个值目前,您的表单只返回一个选项(从PHP的角度来看),因此它只会插入一行。
要遍历该数组,请使用类似以下内容:
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}发布于 2009-06-30 12:42:28
两件事:
<option value="something">行吗?值是空的吗?在我看来,在文件的开头使用$row['strategyname'],然后使用$row['name'],这对我来说很奇怪。我怀疑这可能是StrategyName列为空的原因。额外的[]告诉PHP形成一个包含所有选择的数组。然后,您可以循环遍历数组,如下所示:
$strategylist =$_POST‘策略列表’;for ($i = 0;$i < count($strategylist);$i++) { $strategyname = $strategylist$i;//插入一条记录...}
发布于 2012-05-28 14:53:56
// first you need to define your output as one variable if you don't like the loop
if($_POST){
$sum = implode(", ", $_POST[select2]);
echo $sum.".";
}
// the variable sum is the one you are seeking for you can insert it to the database
// if you want to enter every peiece of the array in a new field you should use
// different select nameshttps://stackoverflow.com/questions/1063385
复制相似问题