What are common pitfalls when creating tables using functions and arrays in PHP?
Common pitfalls when creating tables using functions and arrays in PHP include not properly handling errors or exceptions, not validating input data, and not properly sanitizing user input to prevent SQL injection attacks. To avoid these pitfalls, always validate and sanitize input data, handle errors or exceptions gracefully, and use prepared statements when interacting with a database.
// Example of creating a table using functions and arrays in PHP with proper input validation and sanitization
function createTable($tableName, $columns) {
// Validate input data
if (!is_string($tableName) || empty($tableName) || !is_array($columns) || empty($columns)) {
throw new InvalidArgumentException("Invalid input data");
}
// Sanitize table name
$tableName = filter_var($tableName, FILTER_SANITIZE_STRING);
// Sanitize column names
foreach ($columns as $key => $column) {
$columns[$key] = filter_var($column, FILTER_SANITIZE_STRING);
}
// Create table query
$query = "CREATE TABLE $tableName (";
foreach ($columns as $column) {
$query .= "$column VARCHAR(255), ";
}
$query = rtrim($query, ", ") . ")";
// Execute query (assuming $pdo is a PDO object)
$pdo->exec($query);
}
// Example usage
$tableName = "users";
$columns = ["id", "username", "email"];
createTable($tableName, $columns);