What is the recommended approach for implementing a delete function for database records in PHP?
When implementing a delete function for database records in PHP, it is recommended to use prepared statements to prevent SQL injection attacks. This involves binding parameters to the query to ensure that user input is treated as data rather than executable code. Additionally, it is important to validate user input to ensure that only authorized users can delete records.
<?php
// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Validate user input (e.g. check if user is authorized to delete record)
// Prepare SQL statement with a placeholder for the record ID
$stmt = $pdo->prepare("DELETE FROM table_name WHERE id = :id");
// Bind the record ID parameter
$stmt->bindParam(':id', $record_id, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
Keywords
Related Questions
- Welche potenziellen Probleme können auftreten, wenn ein Header("Location: http://www.domain.com/seite.htm"); am Ende eines PHP-Scripts verwendet wird?
- What best practices should be followed when handling form submissions in PHP to avoid errors?
- How can one optimize PHP code by incorporating additional loops to check for empty variables?