Remembering my first day at work, I used to "sweat" because of a mess of PHP code connected to MySQL, constantly reporting errors and extremely vulnerable to SQL injection. Many newbies are currently struggling in the same way. When looking for instructions online, they only see separate pieces, copied and run with errors all over the place. To understand the root of the problem, many of you often have to re-learn what php is before starting to type the first line of code. This article is not a bunch of empty theories. This is the complete PHP MySQL CRUD connection map that I concluded after 10 years of actual combat in Pham Hai. I will help you go from installing XAMPP, writing absolutely secure CRUD code with PDO, to building a practical RESTful API yourself. After reading and following, you will be completely confident to tackle real projects immediately!
Why Need An "All In One" Guide To PHP MySQL CRUD?
Một hướng dẫn toàn diện giúp bạn nắm bắt luồng dữ liệu xuyên suốt, từ thiết lập database, xử lý logic backend đến trả dữ liệu về frontend mà không bị hổng kiến thức cốt lõi.
When we first step into web programming, we often have the habit of picking up a little bit of code from place to place. As a result, when put together, the application runs with errors and has a messy structure. Having a standard document from start to finish will save you weeks of trying to troubleshoot PHP MySQL database connection errors. At Pham Hai, we always require interns to master the flow of data before touching any complex frameworks.
CRUD - "The Breath" Of Every Dynamic Web Application
CRUD stands for Create, Read, Update, and Delete - the 4 most core operations to interact and manage any database.
Any function you use every day on the internet, from posting a Facebook status, editing personal information, to adding items to your Shopee cart, all revolve around CRUD operations. If you are in the process of Learning basic PHP backend web programming, mastering CREATE, READ, UPDATE, DELETE is the decisive turning point. It turns boring static HTML pages into a truly dynamic web application, capable of storing and responding to user behavior.
Quick Comparison Between MySQLi and PDO: An Inconclusive Battle?
MySQLi only supports connections specifically for the MySQL database management system, while PDO supports up to 12 different database types and is object-oriented and more secure.
When learning how to connect PHP to MySQL?, you will definitely see these two schools of thought. Comparing MySQLi and PDO in connecting PHP MySQL, I always recommend that new users choose PDO from the beginning. Although MySQLi seems accessible thanks to its syntax that resembles plain old PHP, PDO is much more flexible and powerful. Suppose later your project expands and your boss asks you to change from MySQL to PostgreSQL. If you use PDO, you almost don't have to edit the SQL query lines. Đó là lợi thế tuyệt đối của PDO.
SQL Injection Vulnerability: Programmer's "Nightmare" & PDO's Way to the Rescue
SQL Injection is a hacker technique that inserts malicious SQL code into an input form to sabotage or steal data. PDO completely prevents this with the Prepared Statements mechanism.
Hồi mới vào nghề, mình từng suýt "bay màu" cả một bảng dữ liệu khách hàng chỉ vì thói quen nối chuỗi SQL trực tiếp từ dữ liệu người dùng nhập vào. Hacker chỉ cần gõ đoạn mã ' OR 1=1 -- vào ô đăng nhập là qua mặt được hệ thống dễ dàng. Với PDO, dữ liệu đầu vào được tự động "làm sạch" và tách biệt hoàn toàn khỏi câu lệnh thực thi. Cơ chế này giúp mã nguồn của bạn an toàn tuyệt đối trước các cuộc tấn công SQL injection.
Practice Building CRUD Applications From A-Z Like A Pro
This section will guide you to build a CRUD PHP MySQL application step by step, from building a virtual local server to writing query statements that directly manipulate data.
Don't just read with your eyes, open your computer, turn on the editor and type the code with me. This is the most practical CRUD PHP MySQL tutorial for beginners. The goal is to create a simple but standard user management page.
Step 0: Prepare "Playground" - Install XAMPP and Create Database with phpMyAdmin
XAMPP provides a virtual server environment (localhost) that includes PHP and MySQL so you can run dynamic web applications right on your personal computer without buying hosting.
Setting up the XAMPP environment for PHP MySQL CRUD is extremely quick. You just need to download the latest version of XAMPP software to your computer, install (Next continuously) and start the two main modules, Apache and MySQL.
Sau khi hai module này chuyển sang màu xanh, hãy mở trình duyệt và truy cập http://localhost/phpmyadmin. Tại giao diện này, bạn thao tác như sau:
- Tạo một Cơ sở dữ liệu (Database) mới đặt tên là
crud_app. - Bên trong database đó, tạo một Bảng (Table) tên là
users. - Thêm 3 cột cơ bản:
id(kiểu INT, chọn Auto Increment và làm Primary Key),name(kiểu VARCHAR, độ dài 100), vàemail(kiểu VARCHAR, độ dài 100).
Step 1: Create Database Connection Using PDO - Write Once, Use Forever
Use the try-catch block in combination with the PDO object in PHP to create a secure database connection and easily catch errors when there is an incorrect login information.
Để source code gọn gàng và dễ quản lý, bạn nên tạo riêng một file tên là db.php. Việc này áp dụng tư duy tái sử dụng code rất hiệu quả. Nếu bạn đã nắm vững PHP OOP lập trình hướng đối tượng, bạn sẽ thấy cách PDO khởi tạo một instance (đối tượng) cực kỳ quen thuộc và khoa học.
Bạn hãy gõ đoạn code sau vào file db.php:
<?php
$host = 'localhost';
$dbname = 'crud_app';
$username = 'root'; // Mặc định của XAMPP
$password = ''; // Mặc định của XAMPP để trống
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
// Thiết lập chế độ báo lỗi nghiêm ngặt
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Lỗi kết nối CSDL: " . $e->getMessage());
}
?>
Đoạn code trên chính là chuẩn mực ngành để xử lý lỗi kết nối cơ sở dữ liệu PHP MySQL. Hàm die() sẽ lập tức dừng toàn bộ chương trình và in ra màn hình nguyên nhân lỗi nếu database của bạn bị sập hoặc sai mật khẩu.
Step 2: Create - Add New Absolutely Safe Data With Prepared Statements
Sử dụng phương thức prepare() và execute() của PDO để chèn một Bản ghi mới vào bảng mà không sợ bị dính mã độc từ người dùng.
Khi người dùng điền thông tin vào form HTML và nhấn Submit, bạn sẽ hứng dữ liệu đó bằng biến siêu toàn cục $_POST. Thay vì nhét thẳng các biến này vào chuỗi SQL query (rất nguy hiểm), chúng ta sẽ dùng các tham số ẩn danh (như :name, :email).
Tạo file create.php và nhúng file kết nối vào:
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
// Gán giá trị thực tế vào các tham số ẩn danh
if ($stmt->execute(['name' => $name, 'email' => $email])) {
echo "Thêm người dùng thành công!";
}
}
?>
Although this way of writing costs one more line of code compared to the old way, it is "worth the money" because it ensures 100% security for your system.
Step 3: Read - Read and Display Data List
Dùng câu lệnh SELECT kết hợp hàm fetchAll() của PDO để lấy toàn bộ dữ liệu từ database, sau đó dùng vòng lặp foreach để in ra bảng HTML.
Đây là bước bạn móc dữ liệu từ database và hiển thị lên giao diện cho người dùng xem. Tạo file index.php để làm trang chủ hiển thị danh sách. Trong các hệ thống thực tế có hàng triệu bản ghi, việc truy vấn cần được tính toán kỹ. Mình từng có bài viết hướng dẫn tối ưu database mysql wordpress, các nguyên lý tạo index ở đó cũng áp dụng y hệt cho các ứng dụng PHP thuần để tăng tốc độ cho thao tác "Read" này.
<?php
require 'db.php';
$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<table border="1">
<tr>
<th>ID</th>
<th>Tên</th>
<th>Email</th>
<th>Hành động</th>
</tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= $user['id'] ?></td>
<td><?= $user['name'] ?></td>
<td><?= $user['email'] ?></td>
<td>
<a href="update.php?id=<?= $user['id'] ?>">Sửa</a> |
<a href="delete.php?id=<?= $user['id'] ?>">Xóa</a>
</td>
</tr>
<?php endforeach; ?>
</table>
Step 4: Update - Edit Data According to Specific ID
Combine the Read operation (retrieve old data to display on the form) and Update operation (save new data over it) based on the primary key ID transmitted through the URL.
Để làm chức năng sửa, hệ thống cần biết chính xác bạn muốn sửa ai. Đó là lý do chúng ta truyền id qua URL (ví dụ: update.php?id=1). Tại file update.php, bạn dùng lệnh SELECT lấy thông tin user có ID đó đổ vào các thẻ <input>. Sau khi người dùng sửa xong và bấm lưu, bạn dùng lệnh UPDATE để cập nhật.
This is a very typical PHP MySQL CRUD code example, requiring a little logical thinking to not mistakenly update other people's data. Always remember to pass the hidden ID (hidden input) in the update form.
Step 5: Delete - Delete Data From Table
Dùng câu lệnh DELETE FROM kèm theo mệnh đề WHERE để xóa chính xác một dòng dữ liệu, tránh thảm họa xóa nhầm toàn bộ bảng.
Xóa dữ liệu là thao tác dễ code nhất nhưng lại mang rủi ro lớn nhất. Nếu bạn quên mệnh đề WHERE id = :id, toàn bộ bảng users sẽ bốc hơi trong một nốt nhạc.
Một mẹo nhỏ mang tính thực tiễn từ Phạm Hải: Luôn hiển thị một hộp thoại xác nhận (confirm popup) bằng JavaScript (confirm('Bạn có chắc chắn muốn xóa?')) ở giao diện frontend trước khi cho phép mã nguồn PHP thực thi lệnh xóa xuống database.
Level Up Your Skills: From CRUD Applications to Your First RESTful API
API helps your PHP backend application communicate and provide data to other platforms such as mobile apps (iOS, Android) or modern frontend frameworks.
At this point, you have completed a basic web application. But the modern technological world demands more than that. A lot of people text me asking how to create CRUD API with PHP and MySQL? In fact, the essence of writing an API is still a complete PHP MySQL CRUD connection to the database, the only difference lies in the data format you return to the user (Client).
What is a RESTful API? Why Is It So "Hot"?
RESTful API is a network architecture design standard that uses HTTP methods (GET, POST, PUT, DELETE) to manage and exchange resources in JSON format.
Instead of returning a bunch of cumbersome HTML code (like in Step 3), the RESTful API returns pure data. Thanks to that, a single backend system can serve both websites, mobile apps and third-party partners. If you want to go further on the path of professional programming, learning Laravel framework PHP tutorial from scratch will help you automate the creation of these standard RESTful APIs extremely quickly and leisurely.
Turn "Read" Function Into API Endpoint Returning JSON Data
Thay vì dùng thẻ HTML để in dữ liệu, bạn chỉ cần thay đổi Header của trang thành application/json và dùng hàm json_encode() của PHP.
Hãy thử tạo một file mới tên là api_get_users.php. Bạn copy lại đoạn code lấy danh sách user ở Bước 3, nhưng bỏ đi toàn bộ phần HTML.
<?php
require 'db.php';
// Khai báo cho trình duyệt biết đây là dữ liệu JSON
header('Content-Type: application/json');
$stmt = $pdo->query("SELECT id, name, email FROM users ORDER BY id DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Chuyển đổi mảng PHP thành chuỗi JSON và in ra
echo json_encode($users);
?>
Boom! With just a few short lines of code, you can create a great API endpoint yourself. Any device (mobile app, React web) calling this URL will receive the list of users as a JSON array that is extremely easy to read and process.
Use Postman Tool To Test Just Created API
Postman is specialized software that helps simulate requests sent from clients to the server, allowing you to test HTTP methods such as POST, PUT, DELETE easily without needing frontend code.
Khi phát triển API, bạn không thể chỉ dùng trình duyệt web thông thường để kiểm tra, vì trình duyệt mặc định chỉ gửi request dạng GET. Hãy tải phần mềm Postman về máy. Mở Postman lên, chọn method GET, dán đường link http://localhost/crud_app/api_get_users.php vào và nhấn nút Send. Bạn sẽ thấy ngay cục dữ liệu JSON trả về cực kỳ trực quan ở cửa sổ bên dưới. Biết cách sử dụng Postman là kỹ năng sống còn của mọi lập trình viên backend hiện đại.
So you have come a long but extremely worthwhile journey with me. From the first lines of database connection code to building a simple API yourself, you will not only learn complete PHP MySQL CRUD connection techniques but also the mindset of making safe, structured products. Don't just consider this a tutorial, see it as a foundational toolkit for you to confidently conquer more complex web projects in the future.
What steps have you followed? If you have any problems or good ideas during the coding process, don't hesitate to leave a comment below, let's discuss!
Lưu ý: Các thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có được lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.