📘 Lesson · Lesson 16
PHP MySQL Connection (PDO)
Connecting PHP to MySQL
The modern, secure way to connect PHP to MySQL is PDO (PHP Data Objects) with prepared statements, which prevent SQL injection.
Make a Connection
<?php
$host = "localhost"; $db = "school";
$user = "root"; $pass = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected!";
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
}
?>
Safe Query (Prepared Statement)
<?php
$stmt = $pdo->prepare("SELECT * FROM students WHERE marks > ?");
$stmt->execute([80]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row["name"] . "<br>";
}
?>
Why Prepared Statements?
The
? placeholder keeps user input as data, never as runnable SQL. This blocks SQL injection — the #1 web security rule.Summary
- Use PDO to connect PHP to MySQL safely.
- Always use prepared statements (
?placeholders) to prevent SQL injection.
PHP को MySQL से Connect करना
PHP को MySQL से connect करने का modern, secure तरीका PDO (PHP Data Objects) है prepared statements के साथ, जो SQL injection रोकते हैं।
Connection बनाएं
<?php
$host = "localhost"; $db = "school";
$user = "root"; $pass = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected!";
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
}
?>
Safe Query (Prepared Statement)
<?php
$stmt = $pdo->prepare("SELECT * FROM students WHERE marks > ?");
$stmt->execute([80]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row["name"] . "<br>";
}
?>
Prepared Statements क्यों?
? placeholder user input को data रखता है, कभी runnable SQL नहीं। यह SQL injection block करता है — web security का #1 नियम।सारांश
- PHP को MySQL से safely connect करने को PDO use करें।
- SQL injection रोकने को हमेशा prepared statements (
?placeholders) use करें।
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.