php - 使用 PHP 数组显示下拉菜单

标签 php mysql

我有一个 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/

相关文章:

php - 将表单值提交到数据库、php

javascript - 文档更新但 getElementById() 返回不正确的值?

php - 传递回调参数ajax post

mysql - SQL where查询到IN条件的第一行

php - 严格标准 : Declaration should be compatible with PDO statement

mysql - 最不受欢迎的事件 - 获取预订为空或最少的事件列表

php - 如何将表单数据插入MySQL数据库表

php - 我收到类似未捕获异常 'PDOException' 的错误,消息为“SQLSTATE[42000] : Syntax error or access violation: 1064”

php - 在 PHPExcel 中获取不需要的字符,如 "_x000D_"或 "x000D"

php - 自动完成数据分类