![](/img/trans.png)
[英]Can read Data from mysql database but cant write data into the database Using PHP 5.6 on Ubuntu 16.04?
[英]PHP MySQL cant read data from database
下拉列表未顯示我在數據庫中輸入的數據
Product Category:
<select name="product_cat">
<option>Select a Category</option>
<?php
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<option>$cat_title</option>";
}
?>
</select>
試試下面的代碼:
<select name="product_cat">
<option value="">Select a Category</option>
<?php
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
//$cat_id = $row_cats['cat_id']; // no need to put in another variable
//$cat_title = $row_cats['cat_title']; // no need to put in another variable
echo "<option value='".$row_cats['cat_id']."'>".$row_cats['cat_title']."</option>";
}
?>
</select>
您只需要從此更改 while 循環:
while ($row_cats=mysqli_fetch_array($run_cats)){
對此:
while ($row_cats=mysqli_fetch_row($run_cats)){
mysqli_fetch_array()
返回數組中表的所有行。 您需要將它存儲在一個變量中並進行 foreach 循環。
mysqli_fetch_row()
只返回一行。 如果已經獲取了所有行,它也會返回false
,因此您可以像以前一樣在 while 循環中使用它。
<label for='product_cat'>Product Category:
<select name='product_cat'>
<optgroup label='Select a Category'>
<option selected='selected' disabled='disabled' hidden='hidden'>Select a Category
<?php
$sql='select * from `categories`';
$res=mysqli_query( $con, $sql );
if( $res ){
while( $rs=mysqli_fetch_object( $res ) ){
echo "<option value='{$rs->cat_id}'>{$rs->cat_title}";
}
}
mysqli_free_result( $res );
$con->close();
?>
</optgroup>
</select>
</label>
<html>
Product Category:
<?php $get_cats="SELECT * FROM categories"; $run_cats=mysqli_query($con,$get_cats);?>
<select name="product_cat">
<option>Select a Category</option>
<?php while ($row_cats=mysqli_fetch_assoc($run_cats)){?>
<option value="<?php echo $row_cats['cat_id'];?>"><?php echo $row_cats['cat_title']; ?></option>
<?php } ?>
</select>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.