-3

Users can choose an item from a category, and update their choices if they choose to do so. I am displaying the items using the select element. The items are displayed via php to keep the html code succinct.

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

getAllCategories is a function stored in a separate file.

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);   
   }
}

I am able to display this data correctly. Now if the user wants to change the category, he can click the category section and choose any from the drop-down list. Once he clicks the submit button, the POST request runs.

problem: I am unable to get the updated choice of the user, as I get the following message:

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

The code on that line is : $postCategory = $_POST['category_name'];

category_name is defined in the getAllCategories function.

What am I doing wrong?

I've already seen this question, but as I mentioned above, I know what the error means. I have no problem retrieving values from a form or a file. I am having problems with retrieving values from the select element.

Community
  • 1
  • 1
Frosty619
  • 1,381
  • 4
  • 23
  • 33

1 Answers1

2

if u want to get value of a option in php, then use name of select, not option element

$postCategory = $_POST['category_name']; 

change to

$postCategory = $_POST['category'];

$postCategory will return value of selected option

function

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);   
     }
  }
Ōkami X Oukarin
  • 435
  • 5
  • 16