Working with Databases in PHP
Working with databases in PHP involves connecting to a database, performing CRUD operations, and using prepared statements for secure data handling. MySQL is a popular database system used in many PHP applications.
Introduction to MySQL
MySQL is an open-source relational database management system (RDBMS) known for its performance, reliability, and ease of use. It is commonly used with PHP to store and manage data for web applications.
- Key Features:
- Support for SQL queries
- Transactions and concurrency control
- Data security and backup options
Connecting to a MySQL Database
To connect to a MySQL database in PHP, you can use either the mysqli extension or PDO (PHP Data Objects).
- Using
mysqli
:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
- Using PDO:
<?php
$dsn = "mysql:host=localhost;dbname=my_database";
$username = "root";
$password = "";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Performing CRUD Operations
CRUD operations (Create, Read, Update, Delete) are essential for managing data in a database.
-
Create (Insert Data):
- Using
mysqli
:
$sql = "INSERT INTO users (username, email) VALUES ('JohnDoe', '[email protected]')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }
- Using PDO:
$sql = "INSERT INTO users (username, email) VALUES (:username, :email)"; $stmt = $pdo->prepare($sql); $stmt->execute(['username' => 'JohnDoe', 'email' => '[email protected]']);
- Using
Read (Retrieve Data):
- Using
mysqli
:
$sql = "SELECT id, username, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
- Using PDO:
$sql = "SELECT id, username, email FROM users";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "id: " . $row["id"]. " - Name: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
}
Update (Modify Data):
- Using
mysqli
:
$sql = "UPDATE users SET email='[email protected]' WHERE username='JohnDoe'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
- Using PDO:
$sql = "UPDATE users SET email = :email WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->execute(['email' => '[email protected]', 'username' => 'JohnDoe']);
Delete (Remove Data):
- Using
mysqli
:
$sql = "DELETE FROM users WHERE username='JohnDoe'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
- Using PDO:
$sql = "DELETE FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->execute(['username' => 'JohnDoe']);
Prepared Statements and PDO
Prepared statements are used to execute SQL queries securely and efficiently by separating SQL logic from data.
- Using Prepared Statements with mysqli:
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
$username = 'JohnDoe';
$email = '[email protected]';
$stmt->execute();
- Using Prepared Statements with PDO:
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->execute(['username' => 'JohnDoe', 'email' => '[email protected]']);
Working with databases in PHP involves connecting to a database, performing CRUD operations, and using prepared statements for security. Mastering these techniques is crucial for developing robust and secure web applications.