What potential security risk is present in the PHP code provided for deleting a table in a MySQL database?
The potential security risk present in the provided PHP code is SQL injection. The code directly concatenates user input into the SQL query, making it vulnerable to malicious input that can alter the query's logic. To prevent SQL injection, it is recommended to use prepared statements with parameterized queries.
// Fix for preventing SQL injection by using prepared statements
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Using prepared statement to delete a table
$tableName = $_POST['tableName']; // Assuming the table name is received via POST request
$stmt = $mysqli->prepare("DROP TABLE ?");
$stmt->bind_param("s", $tableName);
$stmt->execute();
$stmt->close();
$mysqli->close();
Related Questions
- What are the common pitfalls when using cURL to download files in PHP, and how can they be avoided?
- What are the advantages of using a cost-effective web hosting service with PHP, SQL, and FTP access over setting up PHP on a local machine?
- What are some best practices for debugging PHP code, especially when working with regular expressions?