PHP Fundamentals

Learn PHP programming from scratch, including variables, functions, arrays, and object-oriented programming.

beginner Backend Development 6 hours

Chapter 14: Database Integration

Chapter 14 of 15

Chapter 14: Database Integration

14.1 MySQLi Connection

$conn = new mysqli("localhost", "username", "password", "database");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

14.2 Prepared Statements

$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

14.3 PDO (PHP Data Objects)

$pdo = new PDO("mysql:host=localhost;dbname=database", "user", "pass");
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();