我正在尝试编写一个 php 来从 mysql dba 获取数据,并使用下拉列表中的结果集作为另一个 php 的输入来查询变量。理想情况下,我只想显示姓氏、名字和呼号,同时使用 MembersId 作为表单 php 的参数。
我得到一个要显示的下拉列表,但它没有数据。当我查看源代码时,我看到查询已运行并且可以看到结果集。
我很感激我能得到的任何建议。
<html>
<?php
include('connectDb.php');
$sql="Select MembersId, lastName, firstName, callSign from
SVARC.members";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll();
?>
<form action="LastMeetingAttendancebyDate.php" method="post">
<select name ="user">
<?php
foreach($users as $user){
echo("<option value='");
echo($user['MembersId']+"'>");
echo($user['lastName']);
echo",";
echo($user['firstName']);
echo" ";
echo($user['callSign']);
echo("'</option>");
}
?>
</select>
<input type="submit">
</form>
最佳答案
在这一行:
echo($user['MembersId']+"'>");
您正在尝试使用 +
连接。 PHP 中的串联运算符是 .
.
但是,我建议像这样重写您的代码块:
<select name="user">
<?php foreach ($users as $user): ?>
<option value="<?= $user['MembersId'] ?>">
<?= $user['lastName'] ?>, <?= $user['firstName'] ?> <?= $user['callSign'] ?>
</option>
<?php endforeach ?>
</select>
这利用了 PHP 的 alternative syntax for control structures这对于输出 HTML 等内容特别有用。
我还建议使用htmlspecialchars
值 avoid potential XSS attacks 。为了简单起见,没有将它们添加到示例中,但您至少应该研究一下。
关于PHP <select> 不填充结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54272225/