我只是想显示一个 html <select>
显示来自 MySQL 数据库行的选项的下拉列表。据我所知,这应该有效。但是,它没有在下拉列表中显示任何内容。 campaigns
表肯定在 campaignid
中有数据和 name
列。不知道为什么它不显示任何内容。请帮忙。
应该显示的形式 name
<?php
//include db connect
include ("db_con.php");
//campaign change form function
function changeCampaign() {
//set variables
$query = mysqli_query($con,"SELECT * FROM campaigns");
//echo form
echo '<table border="1">
<form action="functions/campaign_change.php" name="campaignChange" method="post">
<tr>
<td><select name="campaignList">';
//loop campaigns
while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['campaignid'] . "'>" . $row['name'] . "</option>";
}
echo '</select></td>
</tr>
<tr>
<td><input type="submit" value="Load" /></td>
</tr>
</form>
</table>';
}
?>
然后我只需调用 changeCampaign();
函数,它正在显示带有 <select>
的表单只是里面没有内容。
添加了以下代码以显示成功添加到同一个表的脚本
这是创建 campaign
的表单
//campaign creation form function
function createCampaign() {
echo '<table border="1">
<form action="functions/campaign_create.php" name="campaignCreate" method="post">
<tr>
<td><input type="text" name="name" placeholder="Enter Campaign Name" required /></td>
</tr>
<tr>
<td><center><input type="submit" name="Create" /></center></td>
</tr>
</form>
</table>';
}
campaign_create.php
<?php
//include db connect
include ("db_con.php");
//start session
session_start();
//set variable names
$username = $_SESSION['username'];
$campaignname = addslashes($_POST['name']);
//validate campaign name length
if ((strlen($campaignname) < 6) || (strlen($campaignname) > 55)) {
echo 'Campaign name must be between 6 and 55 characters - Please go back and try again.';
exit;
}
//create new campaign
$query = mysqli_query($con, "INSERT INTO campaigns (creator, name) VALUES ('".$username."', '".$campaignname."')");
if ($query) {
echo 'Campaign created successfully!';
header( "refresh:2;url=../index.php" );
} else {
echo 'There was an unknown error in creating the campaign - Please go back and try again.';
}
?>
附言- 是的,campaignid
是表中的一行,其中确实有数据。
最佳答案
首先,您的 <select>
HTML 标签永远不会以 </select>
结束.
二、$con
变量在 changeCampaign
中不可用功能范围。添加global $con;
到函数的开头来修复它。
此外,我更喜欢用这种东西跳进跳出 PHP block 。考虑这段代码:
<?php
//include db connect
include ("db_con.php");
//campaign change form function
function changeCampaign() {
global $con; // we need the connection data in here.
//set variables
$query = mysqli_query($con,"SELECT * FROM campaigns");
?>
<table border="1">
<form action="functions/campaign_change.php" name="campaignChange" method="post">
<tr>
<td><select name="campaignList">';
<?php
//loop that is NOT displaying the name
while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['campaignid'] . "'>" . $row['name'] . "</option>";
}
?>
</select></td>
</tr>
<tr>
<td><input type="submit" value="Load" /></td>
</tr>
</form>
</table>';
<?php
}
?>
在这里,您有输出的 HTML 代码,就像它是 echo
一样。 ed,但它更好。
关于php - 在 <select> 中显示 MySQL 数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22184133/