๐ PHP Database Operations: Your First House Keys
Imagine your database is like a house full of treasures. To get inside, you need the right keys and know how to open doors safely. Today, weโre learning how PHP talks to databases!
๐๏ธ The Big Picture
Think of it this way:
- Database = A big house with many rooms full of information
- PHP = You, standing outside, wanting to get in
- Connection = The key that unlocks the door
- Query = Asking for something inside the house
1. MySQLi Connection ๐ช
MySQLi is like having a special key made just for MySQL houses.
What You Need (The Key Parts)
$host = "localhost"; // Address
$user = "root"; // Your name
$pass = "secret"; // Password
$db = "my_shop"; // Which room?
Opening the Door
$conn = new mysqli(
$host,
$user,
$pass,
$db
);
// Did the door open?
if ($conn->connect_error) {
die("Can't get in!");
}
echo "Welcome inside!";
๐ฏ Simple Explanation
new mysqli()= โPlease make me a keyโ- We give it 4 things: where, who, password, which room
- If the key doesnโt work, we stop and show an error
2. PDO Connection ๐
PDO is like a master key that works on many different house typesโMySQL, PostgreSQL, SQLite, and more!
The Magic Key
$pdo = new PDO(
"mysql:host=localhost;dbname=my_shop",
"root",
"secret"
);
๐ฏ Why PDO is Special
| MySQLi | PDO |
|---|---|
| Only MySQL | Works with 12+ databases |
| Good | Even better for safety |
3. DSN Format ๐
DSN = Data Source Name
Itโs like writing an address on an envelope:
mysql:host=localhost;dbname=my_shop;charset=utf8mb4
โ โ โ โ
driver location room name language
Breaking It Down
graph TD A["DSN String"] --> B["Driver: mysql"] A --> C["Host: localhost"] A --> D["Database: my_shop"] A --> E["Charset: utf8mb4"]
๐ฆ Different House Types (Drivers)
// MySQL house
"mysql:host=localhost;dbname=shop"
// PostgreSQL house
"pgsql:host=localhost;dbname=shop"
// SQLite house (file on disk)
"sqlite:/path/to/database.db"
4. Connection Options โ๏ธ
When you enter a house, you can set rules for how you behave inside.
PDO Options (House Rules)
$options = [
// Show real errors
PDO::ATTR_ERRMODE =>
PDO::ERRMODE_EXCEPTION,
// Get data as arrays
PDO::ATTR_DEFAULT_FETCH_MODE =>
PDO::FETCH_ASSOC,
// Real prepared statements
PDO::ATTR_EMULATE_PREPARES =>
false
];
$pdo = new PDO($dsn, $user, $pass, $options);
๐ฏ What Each Rule Does
| Option | What It Does |
|---|---|
| ERRMODE_EXCEPTION | Screams loudly if something breaks |
| FETCH_ASSOC | Returns data with column names |
| EMULATE_PREPARES | Uses real database preparation |
5. Query Execution ๐ค
A query is like asking a question to the house:
- โWhatโs in the kitchen?โ โ SELECT
- โPut this in the bedroom!โ โ INSERT
- โChange the carpet color!โ โ UPDATE
- โThrow out the old chair!โ โ DELETE
Simple Query (MySQLi)
$result = $conn->query(
"SELECT * FROM products"
);
// Read each item
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
Simple Query (PDO)
$result = $pdo->query(
"SELECT * FROM products"
);
// Read each item
foreach ($result as $row) {
echo $row['name'];
}
๐จ Warning!
Never put user input directly in queries! Bad people can break in!
// โ DANGEROUS!
$pdo->query("SELECT * FROM users
WHERE name = '$userInput'");
// โ
We'll learn the safe way next!
6. Prepared Statements ๐ก๏ธ
Prepared statements are like having a security guard check everyone before they enter.
The Two-Step Dance
graph TD A["Step 1: Prepare"] --> B["Create template with ?"] B --> C["Step 2: Execute"] C --> D["Fill in the blanks safely"]
PDO Example
// Step 1: Prepare the template
$stmt = $pdo->prepare(
"SELECT * FROM users WHERE id = ?"
);
// Step 2: Execute with real value
$stmt->execute([5]);
// Get the result
$user = $stmt->fetch();
MySQLi Example
// Step 1: Prepare
$stmt = $conn->prepare(
"SELECT * FROM users WHERE id = ?"
);
// Step 2: Bind and execute
$stmt->bind_param("i", $userId);
$stmt->execute();
๐ฏ Why This Is Amazing
The ? is like a locked box. Whatever the user types goes INTO the box, never touches the house directly!
7. Binding Parameters ๐
Binding = Connecting your values to the ? placeholders safely.
Two Styles of Placeholders
Style 1: Question Marks (Positional)
$stmt = $pdo->prepare(
"INSERT INTO users (name, age)
VALUES (?, ?)"
);
$stmt->execute(["Alice", 25]);
Style 2: Named Placeholders
$stmt = $pdo->prepare(
"INSERT INTO users (name, age)
VALUES (:name, :age)"
);
$stmt->execute([
':name' => "Alice",
':age' => 25
]);
MySQLi Binding Types
$stmt = $conn->prepare(
"INSERT INTO users (name, age)
VALUES (?, ?)"
);
// "s" = string, "i" = integer
$stmt->bind_param("si", $name, $age);
$stmt->execute();
๐ฏ Type Letters in MySQLi
| Letter | Meaning | Example |
|---|---|---|
| s | String | โhelloโ |
| i | Integer | 42 |
| d | Double (decimal) | 3.14 |
| b | Blob (binary) | images |
๐ Full Working Example
Letโs put it all together!
<?php
// 1. Connection settings
$dsn = "mysql:host=localhost;
dbname=shop;charset=utf8mb4";
// 2. Options for safety
$options = [
PDO::ATTR_ERRMODE =>
PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE =>
PDO::FETCH_ASSOC
];
// 3. Connect!
try {
$pdo = new PDO(
$dsn, "root", "pass", $options
);
} catch (PDOException $e) {
die("Connection failed!");
}
// 4. Prepared statement (SAFE!)
$stmt = $pdo->prepare(
"SELECT * FROM products
WHERE price < :max"
);
// 5. Execute with value
$stmt->execute([':max' => 100]);
// 6. Show results
foreach ($stmt as $product) {
echo $product['name'] . "\n";
}
?>
๐ง Quick Recap
graph TD A["Start"] --> B{Choose Driver} B -->|MySQL only| C["MySQLi"] B -->|Multiple DBs| D["PDO"] C --> E["Create Connection"] D --> E E --> F["Write Query with ?"] F --> G["Prepare Statement"] G --> H["Bind Parameters"] H --> I["Execute Safely!"]
๐ Golden Rules
- Always use PDO unless you have a specific reason for MySQLi
- Never put user input directly in queries - use prepared statements!
- Set error mode to EXCEPTION so you see problems immediately
- Use UTF-8 charset to support all languages
- Close connections when done (PHP does this automatically, but itโs good practice)
You did it! ๐ You now know how to safely open the database door and talk to your data. The house is open, and you have the keys!
