I created a table in mySQL that contains fields such as "name" etc, and I dynamically created several divs (containing a form and a button) relative to how many rows are in that table.
It looks like this :
<?php if ($tabLength > 0) {
for ($x = 0; $x < $tabLength; $x++) {
echo "<div class='data'>
<ul class='data__list bg-grey'>
<li class='data__item name-value'>" . $tab[$x][1] . "</li>
<li class='data__item'>
<div class='data-modifiers'>
<form action='../extern/delete.ext.php' method='post'>
<input type='hidden' name='" . $tab[$x][1] . "' />
<button type='submit' name='delete-submit' class='btn btn-link'>Delete</button>
</form>
</div>
</li>
</ul>
</div>";
}
}
Now I want that when I click the "Delete" button it delete specifically that div.
Thing is, since the inputs's "name" attributes are created dynamically (and which end up being "Bob", "Frank" and whatever for each div's input) I don't know how to use $_POST on the "delete.ext.php file.
Here's my code in delete.ext.php :
<?php
session_start();
if (isset($_POST["delete-submit"])) {
require "dbh.ext.php";
$name = $_POST[' --- what to put in here ? ---']
$sql = "DELETE FROM persons WHERE name='" . $name . "';";
$res = mysqli_query($conn, $sql);
if (!$res) {
header("Location: ../persons/persons.php?error=sqlerror");
exit();
} else {
header("Location: ../persons/persons.php");
exit();
}
}
So, for example, if the "Delete" button I'm clicking on is in the div which contains an input with a dynamically created "name" attribut of "Frank", what should I pass in $_POST to effectively delete specifically that row from the mySQL table ?
Thanks !
Code update :
<?php if ($tabLength > 0) {
for ($x = 0; $x < $tabLength; $x++) {
echo "<div class='data'>
<ul class='data__list bg-grey'>
<li class='data__item name-value'>" . $tab[$x][1] . "</li>
<li class='data__item'>
<div class='data-modifiers'>
<form action='../extern/delete.ext.php'
method='post'>
<input type='hidden' name='name' value='" . $tab[$x][1] . "' />
<button type='submit' name='delete-submit' class='btn btn-link'>Delete</button>
</form>
</div>
</li>
</ul>
</div>";
}
}
And :
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["delete-
submit"]))
{
require "dbh.ext.php";
$sql = "DELETE FROM persons WHERE name= ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_POST['name']);
$res = $stmt->execute();
if (!$res) {
header("Location: ../persons/persons.php?error=sqlerror");
exit;
} else {
header("Location: ../persons/persons.php");
exit();
}
}
this is what's in dbh.ext.php
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "ruchesdb";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if(!$conn) {
die("Connection failed".mysqli_connect_error());
}