PDO (PHP Data Objects) is the modern, database-agnostic way to talk to MySQL from PHP — and unlike the old mysql_* functions, it supports prepared statements by default, closing off SQL injection as a class of bug.
Connecting and Querying
$pdo = new PDO(
"mysql:host=localhost;dbname=shop;charset=utf8mb4",
"dbuser",
"dbpass",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$stmt = $pdo->prepare("SELECT * FROM products WHERE category = ?");
$stmt->execute(['electronics']);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['name'] . "\n";
}
Always Use Prepared Statements
Never build SQL by concatenating user input into a query string. Prepared statements separate the query structure from the data, so user input can never be interpreted as SQL — regardless of what characters it contains.