What are the potential pitfalls of using dynamic table names in PHP when interacting with a MySQL database?
Using dynamic table names in PHP when interacting with a MySQL database can introduce security vulnerabilities such as SQL injection attacks. To prevent this, you should always sanitize and validate user input before using it to construct SQL queries.
// Example of using prepared statements to prevent SQL injection with dynamic table names
$mysqli = new mysqli("localhost", "username", "password", "database");
// Sanitize and validate user input for table name
$table_name = "users"; // Example table name
// Prepare a SQL statement using a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM $table_name WHERE id = ?");
$stmt->bind_param("i", $user_id);
// Execute the statement
$stmt->execute();
// Bind the result
$stmt->bind_result($id, $username);
// Fetch the results
while ($stmt->fetch()) {
echo "ID: $id, Username: $username";
}
// Close the statement and connection
$stmt->close();
$mysqli->close();