我要做的是从MYSQL查询结果填充HTML选择。
有两个文件,这是Food.php:
public function selectBrand()
{
// creating a database connection
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = $this->db_connection->query("SELECT DISTINCT brand_food FROM food;");
$result_row = $query->fetch_object();
echo $result_row->total;
}
这是products.php:
<?php
// include the configs / constants for the database connection
require_once("model/db.php");
require_once("model/Food.php");
$brand = new Food();?>
<div class="panel-body">
<!-- Filter -->
<center>
<form method="post" action="index.php" name="filter_form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" style="box-shadow: 0 0 1px 1px darkgray;"><strong>Brand</strong></span>
<select id="filter_brand" class="form-control" name="brand" style="box-shadow: 0 0 1px 1px darkgray;" required >
<?php
foreach($brand as $brand->selectBrand()){
?>
<option value="<?php echo $brand ?>" ><?php echo $brand ?></option>
<?php } ?>
</select>
</div>
</div>
<input type="submit" name="Filter" value="Filter" class="btn btn-block btn-default"/>
</form>
</center>
<!-- /Filter -->
我之前已经开始工作,但我还没有编码一段时间。 你能帮我吗?
答案 0 :(得分:1)
您的代码有两个问题:
对于模型:
public function selectBrand()
{
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = $this->db_connection->query("SELECT DISTINCT brand_food FROM food;");
$brands = array();
while($obj = $query->fetch_object()){ //fetch each object by while loop
array_push($brands, $obj->brand_food); //push the value into $brands
}
return $brands; //return the array
}
For View(渲染):
<?php foreach($brand->selectBrand() as $brand){ ?>
<option value="<?php echo $brand ?>" ><?php echo $brand ?></option>
<?php } ?>
答案 1 :(得分:0)
这应该有效
public function selectBrand()
{
// creating a database connection
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = $this->db_connection->query("SELECT DISTINCT brand_food FROM food;");
$result_row = $query->fetch_object();
return $result_row->brand_food;
}
<?php foreach($brand->selectBrand() as $brand){ ?>
<option value="<?php echo $brand ?>" ><?php echo $brand ?></option>
<?php } ?>
答案 2 :(得分:0)
您使用foreach的方式错误,请尝试以下代码。我认为你的品牌是阵列。
<?php
foreach($brand->selectBrand() as $select){
?>
<option value="<?php echo $select; ?>" ><?php echo $select; ?></option>
<?php } ?>