简体   繁体   中英

Accessing the ID from one table and inserting it into another table - PHP

Currently I have a form which has dropdown list that contains values that have been accessed from the "Category" table, which has two fields, courseID and cName. This form is in a file called "add_item.php".

<form action="../adminscripts/item_add.php" method="post" class="addItem">
    <label>2) Select Course</label>
                        <br>
                    <select class="dropdown" name="category">
                    <?php 
                    include "..database/connect.php";
                    $query = mysqli_query($conn, "SELECT * FROM courses");
                    while ($row = mysqli_fetch_array($query)){
                    echo "<option value='". $row['cName'] ."'>" . $row['cName'] . " </option>";

                    }
                        ?>

 </select>
 <input class="send" type="submit" value="Add Menu Item" name="itemSubmit">
         </form>

What I am trying to achieve is that when the user selects one of these values, and clicks the "itemSubmit" button, I want the courseID to be posted in the table "menu" along with all the other information on the form. At the moment everything is posted into the database other than the "courseID" which takes the value of "0" when posted in the database.

The form action file "item_add.php" contains the code to submit the information:

<?php
session_start();
    require "../database/connect.php";

    if(isset($_POST['itemSubmit']))
    {
$query2 = mysqli_query($conn, "INSERT INTO menu (mName, courseID, description, price) VALUES ('$itemname', '$courseID', '$item_description', '$price')" ) or die (mysqli_error($conn));

            header("Location:../admin/add_item.php");


            exit;
        }

I have tried to play around with global variables with no luck, hence me having "$courseID" in the above form.

I have not included the file "item_add.php" in the "add_item.php" file because I only need it to fulfil the form action. I have been struggling to access the variable from one file and inserting it into another basically.

Any help?

Apologies, I realised I was missing a "$_POST" variable in "item_add.php" that retrieved the courseID from the dropdown.

This being the variable I was missing

$courseID = $_POST['category'];

I also changed this line

echo "<option value='". $row['cName'] ."'>" . $row['cName'] . " </option>";

to this

echo "<option value='". $row['courseID'] ."'>" . $row['cName'] . " </option>";

so it could retrieve the courseID.

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