How can one prevent SQL injection vulnerabilities when creating database tables dynamically in PHP?

To prevent SQL injection vulnerabilities when creating database tables dynamically in PHP, one should use prepared statements with parameterized queries. This approach ensures that user input is properly sanitized and separated from the SQL query, thus preventing malicious SQL injection attacks.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Define the table name and columns dynamically
$tableName = "users";
$columns = ["id INT(11) AUTO_INCREMENT PRIMARY KEY", "username VARCHAR(50)", "password VARCHAR(255)"];

// Prepare the CREATE TABLE query using parameterized queries
$stmt = $pdo->prepare("CREATE TABLE $tableName (" . implode(", ", $columns) . ")");
$stmt->execute();