0

I'm including a drop down menu and button that deletes the row in a database using php. The value shown in the drop down box (the blog post title) is not the primary key, and the sql delete function only works on the primary key. how can I pass the id to the sql query but still display the title for the blog post?

(yes i do have a connection to the db)

<?php

    $delete = $_POST['delete_submit'];

    mysql_query("DELETE FROM blogpost WHERE BlogPostID=$delete");
    ?>

    <section style="font-size: 22px; text-align: center;">
        <form action='admin.php' method='post' onsubmit="return confirm('Do you really want to delete this post?');">
            <p>
                Delete Post:&nbsp;
                <select name="delete">
                    <option>Please select a post</option>
                    <?php
                    $result = mysql_query("SELECT BlogPostID, BlogPostTitle FROM blogpost ORDER BY BlogPostID DESC");
                    while ($row = mysql_fetch_array($result)){
                        $blogvar  = array($row ['BlogPostID'], $row ['BlogPostTitle']);
                    ?>
                    <option><?php echo $blogvar[1]; ?></option>
                    <?php
                    };
                    ?>
                </select>
                <p></p>
                <input type='submit' class='button' name='delete_submit' value='Delete'/>
            </p>
        </form>
    </section> 
1
  • Fluffeh has provided the mechanism, but you still should probably sanitize the value you receive before sending it to the db. Commented Oct 14, 2013 at 0:58

1 Answer 1

1

You simply put the value in the <option> as follows:

<option value="1">Volvo</option>

This then sends the 1 (or your ID) while still displaying the name.

<option value="<?php echo $blogvar[0]; ?>"><?php echo $blogvar[1]; ?></option>
Sign up to request clarification or add additional context in comments.

3 Comments

You should also make the value of <option>Please select a post</option> equal to -1 so it is the first item in the list and would error out if it was sent to the DB as a value
A value of -1 should not error out. It should simply not delete anything, unless there really was a record with that value.
Hi there when i assign the delete variable how to i pass the value attribute from the option tag to the $delete variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.