Database Basics

Back

Loading concept...

๐Ÿ  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

  1. Always use PDO unless you have a specific reason for MySQLi
  2. Never put user input directly in queries - use prepared statements!
  3. Set error mode to EXCEPTION so you see problems immediately
  4. Use UTF-8 charset to support all languages
  5. 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!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.