PHP PDO Tutorial
What is PHP PDO?
PHP PDO is a way to communicate with databases using PHP. Think of it like talking to your computer\'s brain (the database) to store and retrieve information. We can use it to save data, update it, or delete it when we don't need it anymore.
Setting Up a Connection
To start talking to the database, we need to set up a connection. It\'s like connecting your phone to the internet before using apps. Here's how you do it:
<?php
$host = "your_database_host";
$dbname = "your_database_name";
$username = "your_username";
$password = "your_password";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected successfully!";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
Replace your_database_host
, your_database_name
, your_username
, and your_password
with your actual database information.
Inserting Data
Imagine you have a form on a website where users can add their names and emails. To save this information in the database:
$name = "John Doe";
$email = "john@example.com";
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
if ($stmt->execute()) {
echo "Data inserted successfully!";
} else {
echo "Error inserting data.";
}
This code prepares a statement and safely inserts data into the database to avoid security issues.
Updating Data
Maybe someone wants to change their email address. Here's how you can update it:
$id = 1; // The user you want to update
$newEmail = "new_email@example.com";
$sql = "UPDATE users SET email = :newEmail WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':newEmail', $newEmail);
$stmt->bindParam(':id', $id);
if ($stmt->execute()) {
echo "Data updated successfully!";
} else {
echo "Error updating data.";
}
This code updates the email address for a specific user.
Deleting Data
If someone wants to leave your website, you can delete their account:
$id = 1; // The user you want to delete
$sql = "DELETE FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id);
if ($stmt->execute()) {
echo "Data deleted successfully!";
} else {
echo "Error deleting data.";
}
This code deletes a user from the database based on their ID.
Summary
In this tutorial, we learned how to set up a connection to a database and perform basic operations like inserting, updating, and deleting data using PHP PDO. Think of PDO as your way to talk to the database and store information securely. You can use this knowledge to build cool web applications and handle user data safely.