我有一个 <select multiple="multiple">
在 php 中获得多个选择。之后我把它放在一个变量中 POST
方法,我尝试至少回显数组以确保我的变量 $authors
有选择但它打印此错误
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\ex\addBook.php on line 45
这是我的代码:
<?php
include ("includes/connections.php");
$authors = $_POST["authors"];
foreach ($authors as $author)
{
echo $author;
}
?>
这是我在 html 中的“选择多个”:
<?php multiple("author_ID", "author_firstname", "author_lastname", "author", "author_lastname", "authors"); ?> <span style="font-size: 12px; color: #666;">(Keep down Ctrl for selecting multiple authors)</span>
这里是多重函数:
<?php include ("includes/connections.php");
function multiple($intIdField, $strfNameField, $strlNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
echo "<select multiple=\"multiple\" name=\"$strNameOrdinal\">\n";
$strQuery = "select $intIdField, $strfNameField, $strlNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intIdField"];
$strB = $arrayRow["$strlNameField"] . " " . $arrayRow["$strfNameField"];
echo "<option value=\"$strA \">$strB</option>\n";
}
echo "</select>";
}
?>
所以我猜 $authors
变量将是一个数组,我很乐意至少打印出来,但正如我已经说过的,这不会发生。
从数据库中获取的作者正确显示,没有任何问题。问题是我希望从“选择多个”列表中选择的那些被回显。
最佳答案
HTML 中的多选名称需要以 '[]' 结尾,以表示它是一个数组,然后当你在 php 中运行 foreach 循环时,确保它正在接收一个数组,所以它需要要么被设置,要么您需要将单个值类型转换为数组。不过,我很确定您的问题出在如何设置 name 属性上。
关于php - 在MySQL表中插入多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937328/