Marco
Marco

Reputation: 55

Delete value from Dropdown list

I'm trying to Code a function that allow me to delete a selected value from a Dropdown list.

<?php
require_once("db.inc.php");
?>
</head>
<body>
<form action="" method="POST">
 <?php





$stmt = $mysqli->prepare("SELECT anr, name FROM artikel");
$stmt->execute();
$stmt->bind_result($anr, $name);


echo "<select name='selected_name'><br />";

while ($stmt->fetch()) {

echo '<option value='.$anr.'>'.$anr.' | '.$name.'</option>';


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

    $stmt = $mysqli->prepare("DELETE FROM artikel WHERE anr=?");
        $stmt->bind_param('i', $anr);
        $stmt->execute();
        $stmt->close();
        $mysqli->close();

    }

}   


  ?>
  <input type="submit" value="Datensatz löschen" name="loeschen">
</form>
</body>
</html>

My Problem is that the values are going to be deleted even i don't press the submit button. Thank you in advance for your suggestions.

Upvotes: 3

Views: 67

Answers (2)

Kaja Mydeen
Kaja Mydeen

Reputation: 585

only mistake is instead of this $stmt->bind_param('i', $anr) use below

   $stmt->bind_param('i', $_POST['selected_name']));

Upvotes: 0

Mani
Mani

Reputation: 2655

Use Post value instead of $anr.

<?php
require_once("db.inc.php");
?>
</head>
<body>
<?php
if(isset($_POST['selected_name'])){

    $stmt = $mysqli->prepare("DELETE FROM artikel WHERE anr=?");
        $stmt->bind_param('i', $_POST['selected_name']);
        $stmt->execute();
        $stmt->close();
        $mysqli->close();

    }

}
?>
<form action="" method="POST">
 <?php

$stmt = $mysqli->prepare("SELECT anr, name FROM artikel");
$stmt->execute();
$stmt->bind_result($anr, $name);
echo "<select name='selected_name'><br />";
while ($stmt->fetch()) {
echo '<option value='.$anr.'>'.$anr.' | '.$name.'</option>';
}
echo "</select>";
  ?>
  <input type="submit" value="Datensatz löschen" name="loeschen">
</form>
</body>
</html>

Upvotes: 1

Related Questions