Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Search a table by keyword without SQL injection.
<form method="get">
<input type="search" name="q" placeholder="Search...">
<button>Search</button>
</form><?php
require __DIR__ . '/db.php';
$q = trim((string)($_GET['q'] ?? ''));
$rows = [];
if ($q !== '') {
// escape the LIKE wildcards typed by the user
$safe = addcslashes($q, '%_\\');
$stmt = $pdo->prepare('SELECT id, title FROM articles WHERE title LIKE ? OR body LIKE ? LIMIT 20');
$stmt->execute(['%' . $safe . '%', '%' . $safe . '%']);
$rows = $stmt->fetchAll();
}
foreach ($rows as $r) {
echo '<p>', htmlspecialchars($r['title']), '</p>';
}% and _ are wildcards inside LIKE. Escaping them stops a user from searching for "everything".htmlspecialchars().LIMIT on it so one search cannot return the whole table.LIKE '%word%' cannot use a normal index and is slow on big tables. For large data use a FULLTEXT index (see the advanced tutorial on MySQL full-text search).
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.