我試圖根據從多個選擇框中選擇的選項數量將多行插入到MySQL表中。目前它插入一行(不管選擇了多少選項),但每次「策略名」列都是空的。從多個選擇框向MySQL發送多條記錄
關於如何插入多行以及爲什麼選項的值未被髮送到表的任何想法?
下面的形式:
<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";
?>
謝謝!我已經完成了你所說的要做的事情,現在信息正在傳遞到數據庫中。它將插入兩個選項,但插入同一行,並由昏迷分隔。我理想地喜歡每個選項進入它自己的行。我需要在哪裏插入代碼來遍歷數組?謝謝你的幫助! – user96828 2009-06-30 15:29:35
目前您在插入中使用$ _POST [「strategistist []」],但這是一個數組。我已編輯帖子以說明如何操作。 – 2009-06-30 15:40:01