Php Performing Crud Operations Complete Guide
Understanding the Core Concepts of PHP Performing CRUD Operations
PHP Performing CRUD Operations
CRUD operations are fundamental tasks in web development that facilitate managing data within applications. These include creating new entries, reading or retrieving existing entries, updating certain entries, and deleting others from a database. This comprehensive guide will walk you through each operation using PHP, showcasing examples with both MySQLi (MySQL Improved) and PDO (PHP Data Objects). Both extensions provide powerful tools for interacting with databases securely.
Prerequisites
Before diving into the examples, ensure you have access to a web server running PHP and a MySQL database server. Tools like XAMPP, WAMP, or MAMP can set up this environment easily. Additionally, creating a sample database and table is necessary. For demonstration purposes, consider a simple books
table with columns: id
, title
, author
, year
.
CREATE DATABASE sample_db;
USE sample_db;
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(150) NOT NULL,
year INT NOT NULL
);
Connecting to the Database
Connecting to the database is crucial for performing CRUD operations. Below are examples of connecting to MySQL using both MySQLi and PDO methods.
Using MySQLi
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sample_db";
// 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=sample_db;charset=utf8mb4';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
// Set error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Insert Operation (Create)
Inserting data into the database involves executing an SQL INSERT
statement.
Using MySQLi
<?php
$title = "Harry Potter";
$author = "J.K. Rowling";
$year = 1997;
$sql = "INSERT INTO books (title, author, year) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
if ($stmt === false) {
die("Error preparing the query");
}
$stmt->bind_param("ssi", $title, $author, $year);
$stmt->execute();
echo "New record created successfully";
$stmt->close();
$conn->close();
?>
Using PDO
<?php
$title = "Harry Potter";
$author = "J.K. Rowling";
$year = 1997;
$sql = "INSERT INTO books (title, author, year) VALUES (:title, :author, :year)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':author', $author);
$stmt->bindParam(':year', $year);
$stmt->execute();
echo "New record created successfully";
?>
Select Operation (Read)
Reading data from the database is achieved using an SQL SELECT
query.
Using MySQLi
<?php
$sql = "SELECT id, title, author, year FROM books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Title: " . $row["title"]. " - Author: " . $row["author"]. " - Year: " . $row["year"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Using PDO
<?php
$sql = "SELECT id, title, author, year FROM books";
$stmt = $pdo->query($sql);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row["id"] . " - Title: " . $row["title"] . " - Author: " . $row["author"] . " - Year: " . $row["year"] . "<br>";
}
?>
Update Operation (Update)
Updating data in the database utilizes an SQL UPDATE
statement.
Using MySQLi
<?php
$id = 1;
$newYear = 1999;
$sql = "UPDATE books SET year=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $newYear, $id);
$stmt->execute();
echo $stmt->affected_rows . " record(s) updated";
$stmt->close();
$conn->close();
?>
Using PDO
<?php
$id = 1;
$newYear = 1999;
$sql = "UPDATE books SET year=:year WHERE id=:id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year', $newYear);
$stmt->bindParam(':id', $id);
$stmt->execute();
echo $stmt->rowCount() . " record(s) updated";
?>
Delete Operation (Delete)
Deleting data from the database via an SQL DELETE
statement removes records based on conditions provided.
Using MySQLi
<?php
$id = 1;
$sql = "DELETE FROM books WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
echo $stmt->affected_rows . " record(s) deleted";
$stmt->close();
$conn->close();
?>
Using PDO
<?php
$id = 1;
$sql = "DELETE FROM books WHERE id=:id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
echo $stmt->rowCount() . " record(s) deleted";
?>
Important Notes
Prepared Statements: Always use prepared statements to prevent SQL injection attacks. By preparing your queries and binding parameters, you ensure that user inputs do not alter the structure of your SQL queries.
Error Handling: Proper error handling is essential when working with databases. Use try-catch blocks for PDO and check for errors using MySQLi's error handling mechanisms.
Security: Avoid directly inserting user inputs into SQL queries. Validate and sanitize all data before processing.
Transactions: For scenarios involving multiple related database operations, consider using transactions to ensure data integrity. If one operation fails, others should be rolled back.
Database Management: Keep your database schema up to date and well-documented. Regularly review and optimize your queries for better performance.
Configuration: Store database configuration details like server name, username, and password in a separate file or environment variables and keep them secure.
Performance Optimization: Efficient indexing, proper query structuring, and minimizing database connections can significantly improve performance.
Conclusion
Understanding and implementing CRUD operations effectively in PHP is vital for managing application data seamlessly. Whether leveraging MySQLi or PDO, these extensions offer robust functionalities to interact with MySQL databases while adhering to best practices in security and efficiency. Mastering these operations will lay a strong foundation for crafting dynamic and secure web applications.
Online Code run
Step-by-Step Guide: How to Implement PHP Performing CRUD Operations
Prerequisites
- Basic Knowledge of PHP and HTML.
- A Server Environment (e.g., XAMPP, WAMP, MAMP).
- A Database (e.g., MySQL).
Database Setup
Let's assume we have a simple users
table in our database named testdb
.
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL
);
Step-by-Step Guide to Perform CRUD Operations
1. Setting Up the Database Connection
First, we need to establish a connection to the database using PHP.
db.php
<?php
$servername = "localhost";
$username = "root"; // default username in XAMPP
$password = ""; // default password in XAMPP
$dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
2. Insert Data (CREATE)
Create a form to add new users and process the form submission to insert data into the database.
create_user.php
<!DOCTYPE html>
<html>
<head>
<title>Add User</title>
</head>
<body>
<h2>Add User</h2>
<form action="insert_user.php" method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Create">
</form>
</body>
</html>
insert_user.php
<?php
include 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
3. Read Data (READ)
Display a list of all users from the database.
read_users.php
<?php
include 'db.php';
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>";
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td>
<a href='edit_user.php?id={$row['id']}'>Edit</a>
<a href='delete_user.php?id={$row['id']}'>Delete</a>
</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
4. Update Data (UPDATE)
Create a form to edit user details and process the form submission to update data in the database.
edit_user.php
<?php
include 'db.php';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT id, name, email FROM users WHERE id=$id";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
$name = $row['name'];
$email = $row['email'];
} else {
header("Location: read_users.php");
exit();
}
} else {
header("Location: read_users.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit User</title>
</head>
<body>
<h2>Edit User</h2>
<form action="update_user.php" method="post">
ID: <input type="text" name="id" value="<?php echo $id; ?>" readonly><br>
Name: <input type="text" name="name" value="<?php echo $name; ?>" required><br>
Email: <input type="email" name="email" value="<?php echo $email; ?>" required><br>
<input type="submit" value="Update">
</form>
</body>
</html>
update_user.php
<?php
include 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $conn->real_escape_string($_POST['id']);
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
5. Delete Data (DELETE)
Create a link to delete a user record from the database.
delete_user.php
<?php
include 'db.php';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "DELETE FROM users WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
header("Location: read_users.php");
exit();
}
$conn->close();
?>
Navigation Links
To navigate between the different CRUD operations, you can add links in your HTML files:
index.html
Top 10 Interview Questions & Answers on PHP Performing CRUD Operations
Top 10 Questions and Answers: PHP Performing CRUD Operations
1. What are CRUD operations in PHP?
CRUD stands for Create, Read, Update, and Delete. These are the four basic functions that can be performed on database records via PHP scripts:
- Create: Insert new data into the database.
- Read: Retrieve existing data from the database.
- Update: Modify existing data in the database.
- Delete: Remove data from the database.
2. How do you connect to a MySQL database in PHP?
To connect to a MySQL database, you typically use mysqli_connect()
or PDO (PHP Data Objects) for newer applications. Here’s an example using mysqli
:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
For PDO:
try {
$conn = new PDO("mysql:host=localhost;dbname=myDB", 'username', 'password');
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
3. How do you insert data into a MySQL database using PHP?
You can insert data into a MySQL database using mysqli_query()
for mysqli
or prepared statements with PDO for better security against SQL injection. Here's an example using mysqli
:
$sql = "INSERT INTO Users (username, email) VALUES ('JohnDoe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
And using PDO:
try {
$stmt = $conn->prepare("INSERT INTO Users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$username = "JohnDoe";
$email = "john@example.com";
$stmt->execute();
echo "New record created successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
4. How can you retrieve data from a MySQL database using PHP?
To retrieve records, use SELECT
queries. With mysqli
, it would look like this:
$sql = "SELECT id, username, email FROM Users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Username: " . $row["username"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
Using PDO:
try {
$stmt = $conn->prepare("SELECT id, username, email FROM Users");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
echo $v['id'] . " - " . $v['username'] . " - " . $v['email'] . "<br>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
5. Can you provide an example of updating data in a MySQL database?
Sure, here's how you can update data using both methods.
With mysqli
:
$user_id = 1;
$new_email = 'john_new@example.com';
$sql = "UPDATE Users SET email='$new_email' WHERE id=$user_id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
Using PDO:
try {
$stmt = $conn->prepare("UPDATE Users SET email = :email WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':email', $email);
$id = 1;
$email = 'john_new@example.com';
$stmt->execute();
echo "Record updated successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
6. How do you delete a record from a MySQL database in PHP?
Here’s how to delete a specific record using both methods:
With mysqli
:
$user_id = 1;
$sql = "DELETE FROM Users WHERE id=$user_id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
Using PDO:
try {
$stmt = $conn->prepare("DELETE FROM Users WHERE id=:id");
$stmt->bindParam(':id', $id);
$id = 1;
$stmt->execute();
echo "Record deleted successfully";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
7. Why should I prefer using PDO over mysqli when executing queries?
PDO and mysqli
are both great options but PDO offers several advantages:
- Portability: PDO supports twelve different types of databases, making migrations easier.
- Security: Provides prepared statements which help prevent SQL injection attacks.
- Object-oriented interface: Easier to use for complex queries with object-oriented programming.
- Flexibility: Offers more control over transactions and error handling.
8. How can I handle errors gracefully during database operations in PHP?
Handling errors gracefully ensures your application doesn’t crash if something goes wrong with the database. For PDO:
try {
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// execute query...
} catch(PDOException $e) {
echo "An error occurred: " . $e->getMessage();
}
For mysqli
, check functions’ return values and use mysqli_error()
:
$sql = "INSERT INTO Users (username, email) VALUES ('JohnDoe', 'john@example.com')";
if (!mysqli_query($conn, $sql)) {
throw new Exception("Query failed: " . mysqli_error($conn));
} else {
echo "New record created successfully";
}
9. How do you handle forms in PHP for CRUD operations?
Handling forms involves collecting user inputs in HTML forms and processing them with PHP server-side. Here's a simple form to create a user:
HTML Form:
<form action="create_user.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit">
</form>
create_user.php
:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$uname = $_POST['username'];
$email = $_POST['email'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO Users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $uname, $email);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
10. Can you show how to perform CRUD using AJAX for non-refresh operations?
Absolutely, let's demonstrate how to perform a CREATE operation using AJAX.
HTML:
<div id="user_form">
<input type="text" id="username" placeholder="Username" required>
<input type="email" id="email" placeholder="Email" required>
<button onclick="addUser()">Add User</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function addUser(){
var username = $('#username').val();
var email = $('#email').val();
$.post("users.php",
{
action: "add",
username: username,
email: email
},
function(response){
alert(response);
});
}
</script>
users.php
:
<?php
header('Content-Type: application/json');
$action = $_POST['action'];
$username = $_POST['username'];
$email = $_POST['email'];
$servername = "localhost";
$db_username = "db_username";
$db_password = "db_password";
$dbname = "myDB";
$conn = new mysqli($servername, $db_username, $db_password, $dbname);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
if($action === "add"){
$stmt = $conn->prepare("INSERT INTO Users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();
echo json_encode(['success' => true, 'message'=> 'User added successfully']);
}else{
echo json_encode(['success' => false, 'message'=> 'Invalid action']);
}
}catch(Exception $e){
echo json_encode(['success' => false, 'message'=> 'Database error: '.$e->getMessage()]);
}
$conn = null;
?>
By using AJAX combined with PHP’s PDO or mysqli library in a JSON response format, you can update the webpage dynamically without refreshing the page.
Login to post a comment.