How can a function in PHP be passed the ID of a selected value for the purpose of deleting the corresponding record from a database?
To delete a record from a database based on a selected ID value, you can pass the ID to a PHP function that executes a SQL query to delete the corresponding record. This can be achieved by creating a PHP function that accepts the ID as a parameter and uses it in a DELETE query to remove the record from the database.
<?php
function deleteRecord($id) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to delete record based on ID
$sql = "DELETE FROM table_name WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
}
// Call the function with the selected ID value
$id = $_POST['selected_id'];
deleteRecord($id);
?>