tehX
tehX

Reputation: 167

Inserting dynamic information into the database (dynamic drop-down menu)

I have this code, that gets the categories from the database and displays them on a dropdown menu. Now, what I want to do, Is when something is selected and the button isset, get the ID of that category (table: categories ,row category_id) then submit it into (table: posts ,row category_id). I don't know how to get the ID of the category that was selected in the dropdown. Thanks.
$db variable is the database connection.

This is what I've got so far. This is the submission of the data to the database:

include('../includes/db_connect.php');
if(isset($_POST['submit'])){
    $newTitle = $_POST['newTitle'];
    $newPost = $_POST['newPost'];
    $newCategory = $_POST['newCategory'];
    $my_date = date("Y-m-d H:i:s");
    if(!empty($newPost))
        if(!empty($newTitle)){
    $sql="INSERT INTO posts  (title, body, category_id)
VALUES('$newTitle', '$newPost', '$newCategory')";
    $query = $db->query($sql);
    if($query){
            echo "Post entered to database";
        }else{
            echo "Error Submitting the data";
        }
    }
}

This is the select:

<textarea name="newPost" cols="176" rows="25"/></textarea><br>
<select name=""="newCategory" id="newCategory">
    <option value="0">Select category</option>
<?php
    $result = mysqli_query($db, "SELECT * FROM categories");
    if ( $result ) {
        while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {

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

        }
    } else {
        echo 'Couldn\'t fetch Categories from MySQL.';
    }
?>

Ps - I know this is easily injectable, you don't need to tell me, Just answer the question please :)

Upvotes: 0

Views: 1241

Answers (1)

Pitchinnate
Pitchinnate

Reputation: 7566

You mostly likely just need to change this line, and have the value be the category primary key like id or whatever it is called.

echo "<option value='{$row['id']}'>{$row['category']}</option>";

Otherwise after submit you would have to run a mysql query to find the id by searching where category='$newCategory'

Upvotes: 1

Related Questions