<?php
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
// 1. Create database connection (DSN includes the charset)
$dsn = "mysql:host=$servername;dbname=$dbname;charset=utf8mb4";
$conn = new PDO($dsn, $username, $password);
// 2. Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully.<br><br>";
// ==========================================
// EXAMPLE 1: Inserting data into the database (INSERT)
// ==========================================
// Assuming you have a 'users' table with 'first_name', 'last_name', and 'email' columns
$sql_insert = "INSERT INTO users (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com')";
// exec() is used for queries that don't return a result set
$conn->exec($sql_insert);
// Get the ID of the last inserted row
$last_id = $conn->lastInsertId();
echo "✅ New record created successfully. The ID of the new user is: " . $last_id . "<br><br>";
echo "<hr>";
// ==========================================
// EXAMPLE 2: Reading data from the database (SELECT)
// ==========================================
$sql_select = "SELECT id, first_name, last_name FROM users";
// query() is used for running standard SELECT statements
$stmt = $conn->query($sql_select);
// Check if the query returned any rows
if ($stmt->rowCount() > 0) {
echo "<strong>User List:</strong><br>";
// Loop through the results row by row using FETCH_ASSOC
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row["id"] . " | Name: " . $row["first_name"] . " " . $row["last_name"] . "<br>";
}
} else {
echo "No records found in the database.";
}
} catch (PDOException $e) {
// Catch any database errors and display them safely
echo "❌ Database Error: " . $e->getMessage();
}
// 3. Close the connection
// In PDO, closing the connection is done by setting the variable to null
$conn = null;
?>