无法获取html5';s<;选项>;元素以在PHP中显示值


unable to get html5's <option> element to display value in PHP

用户可以从类别中选择一个项目,并在选择时更新他们的选择。我使用select元素显示这些项目。这些项通过php显示,以保持html代码简洁。

     <div class="form-group">   
        <label for="category">category</label>
         <select name="category" id="">               
<?php
    getAllCategories();
?>          
         </select>
     </div>

getAllCategories是一个存储在单独文件中的函数。

function getAllCategories() {
global $connection;
$categoryQuery = "SELECT * FROM categories";
$runCategoryQuery = mysqli_query($connection, $categoryQuery);

checkQuery($runCategoryQuery);                               
$row = mysqli_fetch_assoc($runCategoryQuery);
while ($row) {

    $categoryName = $row['category_name'];  
    $categoryId = $row['category_id']; 
    echo "<option value='' name='category_name'> $categoryName </option>";

     $row = mysqli_fetch_assoc($runCategoryQuery);   
   }
}

我能够正确显示这些数据。现在,如果用户想要更改类别,他可以单击类别部分并从下拉列表中选择任何类别。一旦他点击提交按钮,POST请求就会运行。

问题:我无法获得用户的更新选择,因为我收到以下消息:

notice: Undefined index: category_name in /Applications/XAMPP/xamppfiles/htdocs/demo/cms/admin/includes/edit_post.php on line 8

那一行的代码是:$postCategory = $_POST['category_name'];

category_name是在getAllCategories函数中定义的。

我做错了什么?

我已经看到了这个问题,但正如我上面提到的,我知道这个错误意味着什么。从表单或文件中检索值没有问题。我在从select元素检索值时遇到问题。

如果你想在php中获得选项的值,那么使用select的名称,而不是选项元素

$postCategory = $_POST['category_name']; 

更改为

$postCategory = $_POST['category'];

$postCategory将返回所选选项的值

功能

function getAllCategories() {
  global $connection;
  $categoryQuery = "SELECT * FROM categories";
  $runCategoryQuery = mysqli_query($connection, $categoryQuery);

  checkQuery($runCategoryQuery);                               
  $row = mysqli_fetch_assoc($runCategoryQuery);
  while ($row) {

      $categoryName = $row['category_name'];  
      $categoryId = $row['category_id']; 
      echo "<option value='".$categoryId."'> $categoryName       </option>";

       $row = mysqli_fetch_assoc($runCategoryQuery);   
     }
  }