I'm new to PHP and MySQL . I'm using PHP to display table contents and I added a button that will remove a row once it's clicked. I'm can't get the button to use delete.php to remove a row from the table and from the database. Any suggestions ?
Thank you
shopping-bag.php
<table>
<tr>
<th>ITEM</th>
<th>MODEL</th>
<th>QUANTITY</th>
<th>COLOR</th>
<th>PRICE</th>
</tr>
<?php
$conn = mysqli_connect(
"localhost",
"user",
"pass",
"db"
);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT productname, productmodel, productquantity,
productcolor, productprice FROM posts";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["productname"] . "</td><td>" .
$row["productmodel"] . "</td><td>"
. $row["productquantity"] . "</td><td>" .
$row["productcolor"] . "</td><td>"
. "$" . $row["productprice"] . "</td><td>" . "<input type='button' name='removerow' action='delete.php' value='REMOVE'>" . "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</table>
delete.php
<?php
$host = "localhost";
$dbusername = "user";
$dbpassword = "pass";
$dbname = "db";
//Connect
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
//DELETE query
if (mysqli_connect_error()) {
die('Connect error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
} else {
$sql = "DELETE FROM posts WHERE ID = '$_GET[id]'";
if (mysqli_query($conn, $sql)) {
header("refresh:1; url=shopping-bag.php");
} else {
echo "NOT DELETED";
}
}
?>
In shopping-bag.php, you need to retrieve ID in your loop over the SELECT
statement results, and put it as an argument to action='delete.php?id=$id'
.
Also recommend reading cross-site scripting and SQL injection so you can avoid these common vulnerabilities in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.