我有一个 php 函数,可以从数据库中获取作者列表...我试图将此列表显示在下拉菜单上,因此当用户按作者选择时,它会显示为列表作者组成数据库...我不想手动输入作者,但我希望它使用该函数来填充列表..这是我的 getAuthors 函数
<?php
function getAuthors($db, $isbn)
{
$query = 'SELECT first_name, last_name
FROM books_authors
INNER JOIN authors ON authors.author_id = books_authors.author_id
WHERE isbn = :isbn
ORDER BY author_ordinal';
$statement = $db->prepare($query);
$statement->bindValue(':isbn', $isbn);
$statement->execute();
$authors = $statement->fetchAll();
$statement->closeCursor();
$authorString = "";
$count = 1;
foreach ($authors as $author)
{
$authorString = $authorString . $author['first_name'] . ' ' . $author ['last_name'];
if ($count < $statement->rowCount())
$authorString = $authorString . ", ";
$count++;
}
return $authorString;
}
?>
这是我的下拉菜单
<select name ="searchtype">
<option value="author"> By author: </option>
最佳答案
if(stcmp($ishtml,"yes")== 0)
{ ?>
<select name ="searchtype">
<option value="author"> By author: </option>
<? } foreach ($authors as $author)
{
$authorString = $authorString . $author['first_name'] . ' ' . $author ['last_name'];
if ($count < $statement->rowCount())
$authorString = $authorString . ", ";
$count++;
if(stcmp($ishtml,"yes")== 0)
{
?> <option value="<? echo $authorString; ?>"> <? echo $authorString; ?> </option>
<?
}
}
只需用我的代码更改你的 foreach 代码就可以了,你可以向函数添加一个默认参数来询问是否显示 html 代码。
更改您的函数 header :
function getAuthors($db, $isbn,$ishtml="no")
{
... code below
}
因此,现在要打印下拉列表,您需要使用附加参数“yes”来调用函数。就是这样
关于php - 使用 PHP 数组显示下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40400106/