[英]populate dropdown menu on html page from database using php
我正在尝试从数据库中填充一个下拉菜单,但是当我运行代码时,我没有收到任何错误,但是输出显示了我的代码的一部分,没有正确的结果。
index.html
页面上的代码是
<section id="services" class="emerald">
<div class="container">
<div class="row">
<div class="row">
<div class="col-md-4 col-sm-6">
<div class="media">
<div class="media-body">
<?php
$servername = "localhost";
$username = "username";
$password = "pwd";
$dbname = "db";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT treatment_type FROM treatment_type";
$result = $con->query($sql);
echo "<label for='treatment_type'>Treatment Type: </label>";
echo "<select name='treatment_type' id='treatment_type' class='form-control'>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['treatment_type'] . "'>" . $row['treatment_type'] . "</option>";
}
echo "</select>";
?>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
我与盒子相处的输出是query($sql); echo "Treatment Type: "; echo "
query($sql); echo "Treatment Type: "; echo "
query($sql); echo "Treatment Type: "; echo "
,下拉菜单应显示的位置显示为".$row['treatment_type']."
然后,正如我在评论中提到的那样:“但是输出显示了我的代码的一部分,没有正确的结果”是不是意味着您看到了代码? 然后,您需要将.html替换为.php或将您的配置设置为将.html解析为php。
这是给以后问这个问题的用户的。
首先,您应该将文件类型更改为.php
然后如kern所述,您应该查看MVC框架,现在我要做的就是将连接移至类中的函数
此示例使用的是ODBC连接,但要点相同,只是将其更改为mysqli或使用PDO
public static function functionName($variableToPassToQuery) {
//Change this part so you are connecting to your database
$conn = odbc_connect('SomeDatabase', '', '');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
// Change to the SQL you need
$sql = "SELECT * FROM Somewhere WHERE Something = $VariableToPassToQuery)";
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
//then once the query has been run we need to get the results and put them in to an array
while ($data = odbc_fetch_array($rs)) {
$row[] = $data;
}
//And then return that array
return $row;
}
把所有这些都放在一堂课上
现在,在您应该更改为PHP文件的HTML文件中,我们可以像这样进行下拉框
因此,在表单内部,您需要告诉它我们需要一个下拉框
<select name="dropdown">
<?php
//then for each of the results in the array we need to an an option
//call the function from the class like this Classname::Functionname($variable) of course if you
//don't need to pass a variable then dont
foreach (Classname::functionName($variableToPassToQuery) as $a) {
echo '<option value=' . $a["SecondRef"] . '>' . $a["Description"] . ' </option>';
}
?>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.