Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Download a table as CSV and read an uploaded CSV safely.
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="customers.csv"');
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF"); // BOM so Excel reads UTF-8
fputcsv($out, ['ID', 'Name', 'Email']);
foreach ($pdo->query('SELECT id, name, email FROM customers') as $row) {
fputcsv($out, $row);
}
fclose($out);<?php
$tmp = $_FILES['csv']['tmp_name'] ?? '';
if (!is_uploaded_file($tmp)) exit('No file');
$h = fopen($tmp, 'r');
fgetcsv($h); // skip header row
$stmt = $pdo->prepare('INSERT INTO customers (name, email) VALUES (?, ?)');
$pdo->beginTransaction();
while (($row = fgetcsv($h)) !== false) {
if (count($row) < 2) continue;
if (!filter_var($row[1], FILTER_VALIDATE_EMAIL)) continue;
$stmt->execute([trim($row[0]), trim($row[1])]);
}
$pdo->commit();
fclose($h);fputcsv and fgetcsv. Splitting on commas yourself breaks when a value contains a comma or a quote.=, +, - or @ as formulas. When exporting user text, prefix such values with a '.Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.