What are some best practices for creating multiple SQL tables in PHP using loops or arrays?

When creating multiple SQL tables in PHP, using loops or arrays can help streamline the process and make the code more maintainable. One approach is to define an array of table names and their corresponding column definitions, then loop through this array to create each table dynamically. This allows for easy scalability and organization of the table creation process.

<?php

// Define an array of table names and their column definitions
$tables = [
    'users' => 'id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50)',
    'products' => 'id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), price DECIMAL(10,2)'
];

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Loop through the array and create each table dynamically
foreach ($tables as $tableName => $columns) {
    $sql = "CREATE TABLE IF NOT EXISTS $tableName ($columns)";
    $pdo->exec($sql);
    echo "Table $tableName created successfully.<br>";
}

?>