How can PHP developers avoid SQL injection when dynamically assigning table names in queries?
To avoid SQL injection when dynamically assigning table names in queries, PHP developers should use prepared statements with parameterized queries. This method separates the SQL query logic from the data being passed, preventing malicious SQL injection attacks.
// Example of using prepared statements to avoid SQL injection when dynamically assigning table names in queries
// Initialize variables
$tablename = $_GET['tablename']; // Assuming the table name is passed via GET parameter
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare the SQL query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM $tablename WHERE id = ?");
$stmt->bind_param("i", $id);
// Set parameters and execute the query
$id = 1;
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process each row
}
// Close the statement and connection
$stmt->close();
$conn->close();
Related questions
-
PHP code organization include statement code duplication
-
server configurations file extensions PHP
-
PHP classes member function