Frage

The following code displays a list of artists (they are stored in the Artists table) with the use of their id. What I have not managed to do, is to delete an artist by selecting him in the dropdown list.

Here is the code if the delete button is pressed:

 if (isset($_POST['delete'])) { 

 $id = $_POST['id'];

 $deleteAlbumSqlQuery = "delete from Artists where Id = $id";

 $deleteResult = mysqli_query($mysqli, $deleteAlbumSqlQuery) or die ($deleteAlbumSqlQuery . " " .    mysqli_error($mysqli));

$display_html .= "Artist " . $id . " Deleted!"; }

And here the code of the dropdown list:

        $sql = 'Select Id, Name from Artists order by Name';
        $result2 = mysqli_query($mysqli,$sql);
        ?>
        <select name="Id"> <?php
        if (mysqli_num_rows($result2) > 0) {

            while ($data = mysqli_fetch_array($result2)) {
                        $cid = $data['Id'];
                        $cname = $data['Name']; ?>
                        <option value="<?php echo $cid; ?>">  <?php echo $cname; ?> </option> <?php
            }                   
        }
?>      
            </select>

The problem is that I cannot figure how am I going to connect them. Everything I've tried so far didn't work, so any help would be happily accepted!

War es hilfreich?

Lösung

Your <select> element should be within a <form> element. (by the way you should rename your select element from Id to id as you are expecting Id in your PHP block. You can also change if block to check $_POST['id'] instead of $_POST['delete'])

Then, you should submit this form either via javascript or with a submit button.

BTW: You better cast posted id to integer to prevent sql injection

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top