我只是想显示一个显示MySQL数据库行选项的html <select>
下拉列表。据我所知,这应该是有效的。但是,它没有在下拉列表中显示任何内容。 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>';
}
<?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.';
}
?>
P.S。 - 是的,campaignid
是表格中的一行,并且其中包含数据。
答案 0 :(得分:1)
您需要回显一个关闭的选择标记。只需在循环后添加此行,就可以了。
echo '</select>';
还可以尝试将循环的第一行更改为:
while ($row = mysqli_fetch_array($con, $query)) {
答案 1 :(得分:1)
首先,您的<select>
HTML代码永远不会被</select>
关闭。
其次,$con
函数范围内的changeCampaign
变量不可用。将global $con;
添加到函数的开头以进行修复。
另外,我喜欢用这种东西跳进和跳出PHP块。请考虑以下代码:
<?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
编辑一样,但它更好。