简体   繁体   中英

how to insert id from dropdown menu in database

I have 2 tables category and subcategory. I wish to add subcategory into database after selecting a category from dropdown. In the subcategory table i am able to save the catname and subcatname, however i also wish to save the catid corresponding to the catname selected( auto increment id of category table) in the subcategory table without showing it to the user. Can anyone tell how i can do so

category table

id catname
1    C1
2    C2

subcategory table

id  catid   catname   subcatname
1            C1        S1

form to add subcategory

<form action="a_insert_subcategory.php" method="post">
    <label>Category</label>
        <select name="catname">
            <?php
                require 'connection.php';
                $sql = "SELECT * FROM category";
                $result = mysqli_query($con, $sql);
                if (mysqli_num_rows($result) > 0) 
                    {
                        while($row = mysqli_fetch_assoc($result)) 
                            {
                                $catname=$row["catname"];
            ?>

            <option value="<?echo $catname;?>"><? echo $catname;?></option>
                          <?}
                    }?>
        </select>

    <label>Subcategory</label>
    <textarea rows="2" name="subcategory"></textarea>

    <input type="submit" name="submit" value="Submit" class="alt_btn">
</form>

code for a_insert_subcategory.php is

<?php
require 'connection.php';

$catname= mysqli_real_escape_string($con, $_POST['catname']);
$subcategory = mysqli_real_escape_string($con, $_POST['subcategory']);

$sql="INSERT INTO subcategory(catname,subcatname) VALUES ('$catname','$subcategory')";

if (!mysqli_query($con,$sql)) 
    {
        die('Error: ' . mysqli_error($con));
    }

mysqli_close($con);
?>

You can try using jQuery to get $_POST['catid']

<form action="a_insert_subcategory.php" method="post">
    <div class="module_content">
        <fieldset>
            <label>Category</label>
                <select name="catname" id="catname">
                    <?php
                        require 'connection.php';
                        $sql = "SELECT * FROM category";
                        $result = mysqli_query($con, $sql);
                        if (mysqli_num_rows($result) > 0) 
                            {
                                while($row = mysqli_fetch_assoc($result)) 
                                    {
                                        $catname=$row["catname"];
                                        $catid=$row["catid"];
                    ?>

                    <option data-id=<?php echo $catid; ?> value="catname"><? echo $catname;?></option>
                                  <?}
                            }?>
                </select>
                <input type="hidden" name="catid" id="catid">
                <script>
jQuery(document).ready(function($) {
    jQuery(document).on('change', '#catname', function(event) {
       jQuery('#catid').val(jQuery('#catname option:selected').data('id'));
    });
});
                </script>
        </fieldset>     

        <fieldset>
            <label>Subcategory</label>
            <textarea rows="2" name="subcategory"></textarea>
        </fieldset>

    </div>
    <footer>
        <div class="submit_link">
            <input type="submit" name="submit" value="Submit" class="alt_btn">
        </div>
    </footer>
</form>

Take note of the script tags as well as the new form input with a type of hidden.

To start with where you have

<option value="catname"><? echo $catname;?></option>

You will need to change it to something like this:

<option value="<? echo $row['id']; ?>"><? echo $catname;?></option>

This puts the ID of the category in each option of your select statement.

And then in your a_insert_subcategory.php you would be able to access the category ID with $_POST['catname'] (you'll probably want to rename your select). Note that you will no longer have access to the category name through the $_POST variable (actually I don't think you have that now either). So you will need to look that up from your database (although, to be properly normalized and avoiding data redundancy you should be storing your category name only in the category table and then looking it up by ID).

You can store the $_POST['category'] in a variable, pass it to a function which queries your category table and return its ID.

function getCatId($Catname)
{
  $query = "select id from CATEGORY_TABLE where catname='$Catname' ";
  $result = mysqli_query($query);
  while($row = mysqli_fetch_array($result))
      {
         $CatID = $row['id'];
      }
  return $CatID;
}

There are two solutions:

  1. in the <option value="catname"><? echo $catname;?></option> <option value="catname"><? echo $catname;?></option> line you can use <option value="<? echo $row['id'];?>"><? echo $catname;?></option> <option value="<? echo $row['id'];?>"><? echo $catname;?></option> and in the insert_subcategory.php file

      <?php require 'connection.php'; $category_id = mysqli_real_escape_string($con, $_POST['category']); $subcategory = mysqli_real_escape_string($con, $_POST['subcategory']); $catQuery = "SELECT catname FROM category WHERE id = ".$category_id." LIMIT 1"; $catRes = mysqli_query($catQuery); $catRow = mysqli_fetch_assoc($catRes); $sql="INSERT INTO subcategory(catid,catname,subcatname) VALUES ($category_id,'".$catRow['catname']."','$subcategory')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } mysqli_close($con); ?> 
  2. 1st solution will not show id to the user still if you dont want to use id in the value just use <option value="<? echo $catname;?>"><? echo $catname;?></option> <option value="<? echo $catname;?>"><? echo $catname;?></option> and in the insert_subcategory.php file

      <?php require 'connection.php'; $category = mysqli_real_escape_string($con, $_POST['category']); $subcategory = mysqli_real_escape_string($con, $_POST['subcategory']); $catQuery = "SELECT id FROM category WHERE catnme = '".$category."' LIMIT 1"; $catRes = mysqli_query($catQuery); $catRow = mysqli_fetch_assoc($catRes); $sql="INSERT INTO subcategory(catid,catname,subcatname) VALUES (".$catRow['id'].",'$category','$subcategory')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } mysqli_close($con); ?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM