【发布时间】:2018-10-30 03:23:57
【问题描述】:
我正在使用 PHP 和 MySQL,我想从 db 中检索一些数据到一个 select html 标记中。
我所做的是:
<select class='form-control select2' name='product_cat' style='width: 100%;'>
".get_cats()."
</select>
而函数get_cats 是这样的:
function get_cats(){
$get_cats = "select * from categories";
$run_cats = mysqli_query($GLOBALS['con'],$get_cats);
$return = '';
while($row_cats = mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$table_id = $row_cats['table_id'];
$cat_title = $row_cats['cat_title'];
$totalNumberOfProductsQuery = "SELECT * FROM products WHERE product_cat = '" . $cat_id. "'";
$catsProducts = mysqli_query($GLOBALS['con'], $totalNumberOfProductsQuery);
if (!$catsProducts) {
die(mysqli_error($GLOBALS['con']));
}
$totalProductsForCats = mysqli_num_rows($catsProducts);
echo "
<option value='$cat_id'>$cat_title</option>
";
}
}
它只是正确地从数据库中抓取数据,但问题是,它以这种方式打印出来:
当产品类别字段为空并且选择标签的选项在表单字段中上升时。
我猜这个问题是因为我在函数中使用了while() 语句。
使用另一个命令执行此功能的替代方法是什么?如何在此函数中正确放置选项列表?
谢谢。
【问题讨论】:
-
为此使用
htmlspecialchars -
尝试从 php 表单中显示更多代码。从我看来是正确的
标签: php function mysqli while-loop