gpt4 book ai didi

php - 在 PHP 中使用对 MySQL 的单个 mysqli_fetch_array() 查询填充多个下拉列表

转载 作者:行者123 更新时间:2023-11-29 05:06:26 25 4
gpt4 key购买 nike

我在填充多个下拉菜单时遇到问题。我需要通过对数据库的单个查询来完成,是否可以在单个 while 循环中完成?这是代码。只有第一个下拉列表(Player)被填充。数据库表(playerDB)有 2 列 - Player 和 Game。并且需要填充相应的下拉列表

 <form name="form1" action="" method="post">
<fieldset>
<legend>Selecting report</legend>
<p>
<?php
$connect = mysqli_connect('localhost','root','','mydatabase');

if(mysqli_connect_errno($connect))
{
echo 'Failed to connect';
}
else{
echo '';
}

if (!$res=mysqli_query($connect, "SELECT * from playerDB")){
echo ("Error description: " .mysqli_error($connect));
}
?>

<label>Select Player</label>
<select>
<?php
while($row=mysqli_fetch_array($res))
{
?>
<option> <?php echo $row["Player"]; ?> </option
<?php
}
?>
</select>

<label>Select Game</label>
<select id = "myGameList">
<?php
while($row=mysqli_fetch_array($res))
{
?>
<option> <?php echo $row["Game"]; ?> </option>
<?php
}
?>
</select>

任何帮助将不胜感激,谢谢!

最佳答案

1. 不要使用 while() 来填充选择框,而是尝试将记录保存在数组中,然后将该数组用作多次。

2. 还尝试仅获取那些您实际进一步需要的列。它将使查询更轻,记录数组也更轻。

像下面这样:-

<?php
$connect = mysqli_connect('localhost','root','','mydatabase');

if(mysqli_connect_errno($connect))
{
echo 'Failed to connect';
}
else{
if (!$res=mysqli_query($connect, "SELECT Player,Game from playerDB")){ // get that much column only which you want not all
echo ("Error description: " .mysqli_error($connect));
}
}
$data = []; //create array
while($row=mysqli_fetch_array($res))
{
$data['Player'][] = $row["Player"]; //assign values to array
$data['Game'][] = $row["Game"];//assign values to array
}
?>


<form name="form1" action="" method="post">
<fieldset>
<legend>Selecting report</legend>
<label>Select Player</label>
<select>
<?php
foreach ($data['Player'] as $player){//use array as many times you want
?>
<option> <?php echo $player; ?> </option
<?php
}
?>
</select>
<label>Select Game</label>
<select id = "myGameList">
<?php
foreach ($data['Game'] as $game){//use array as many times you want
?>
<option> <?php echo $game; ?> </option>
<?php
}
?>
</select>

关于php - 在 PHP 中使用对 MySQL 的单个 mysqli_fetch_array() 查询填充多个下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47069681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com