


Building a PHP CRUD Application with OOP and MySQL: A Best Practice Guide
Jan 11, 2025 am 07:20 AMEfficiently managing database operations is crucial for PHP application development. CRUD (Create, Read, Update, Delete) is one of the most common database operations. Adopting object-oriented programming (OOP) principles can help make your code simpler and easier to reuse and extend. Using MySQL with PHP also ensures that your application can handle data storage efficiently.
This blog post will walk you through how to build a PHP CRUD application using OOP and MySQL. We'll follow best practices and design patterns to organize the code so that it's beginner-friendly yet powerful enough to be used on larger projects.
After reading this guide, you will have a solid foundation for working with databases using OOP principles in PHP.
Table of Contents
- The importance of OOP in PHP
- Project Settings
- Create database
- Folder structure
- Connect to database
- Create CRUD operations
- Create
- Read
- Update
- Delete
- Summary
1. The importance of OOP in PHP
Object-oriented programming (OOP) is a programming paradigm that uses "objects" to organize code. In PHP, OOP allows you to create classes that represent real-world entities, making your code more modular, easier to reuse, and easier to manage.
Applying OOP principles when working with databases means:
- Separation of Concerns: Database logic is encapsulated in a class, separate from the rest of the application logic.
- Reusability: You can reuse database classes in multiple parts of your application.
- Maintainability: As your application grows, your code is easier to update and extend.
2. Project settings
Before we start coding, let’s set up an easy-to-maintain folder structure. Your project should be organized as follows:
<code>php-crud/ ├── config/ │ └── Database.php ├── controllers/ │ └── UserController.php ├── models/ │ └── User.php ├── views/ │ └── user_list.php ├── public/ │ └── index.php └── .gitignore</code>
- config/Database.php: Contains database connection logic.
- controllers/UserController.php: Handles CRUD operations and communicates with the model.
- models/User.php: Contains logic for interacting with the users table in MySQL.
- views/user_list.php: Display user data in table form.
- public/index.php: The entry point of the application.
3. Create database
Let’s start by creating the database and users table in MySQL. You can execute the following SQL query to set up the database:
CREATE DATABASE php_crud; USE php_crud; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
This table will store basic user information such as name, email, and creation date.
4. Folder structure
We have set up the basic folder structure. Here's a breakdown of what each folder does:
- config/: Contains database configuration and connection logic.
- controllers/: Handle the request and call the corresponding method in the model.
- models/: Represents business logic and database interaction.
- views/: Display data to the user.
- public/: The public folder contains the index.php file, which will serve as the entry point to the application.
5. Connect to database
Let’s start by creating a database connection class in config/Database.php:
<code>php-crud/ ├── config/ │ └── Database.php ├── controllers/ │ └── UserController.php ├── models/ │ └── User.php ├── views/ │ └── user_list.php ├── public/ │ └── index.php └── .gitignore</code>
This class creates a PDO connection to MySQL and is reusable in your project.
6. Create CRUD operations
Let’s create a model for handling user data. This class will interact with the users table and perform CRUD operations.
Create model (User.php)
CREATE DATABASE php_crud; USE php_crud; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Create Controller (UserController.php)
<?php namespace Config; use PDO; class Database { private $host = '127.0.0.1'; private $dbName = 'php_crud'; private $username = 'root'; private $password = ''; private $connection; public function connect() { try { $this->connection = new PDO( "mysql:host={$this->host};dbname={$this->dbName}", $this->username, $this->password ); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection; } catch (PDOException $e) { die("Database connection failed: " . $e->getMessage()); } } }
Create view (user_list.php)
<?php namespace Models; use Config\Database; class User { private $conn; public function __construct() { $database = new Database(); $this->conn = $database->connect(); } public function create($name, $email) { $sql = "INSERT INTO users (name, email) VALUES (:name, :email)"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); return $stmt->execute(); } public function read() { $sql = "SELECT * FROM users"; $stmt = $this->conn->prepare($sql); $stmt->execute(); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } public function update($id, $name, $email) { $sql = "UPDATE users SET name = :name, email = :email WHERE id = :id"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); $stmt->bindParam(':id', $id); return $stmt->execute(); } public function delete($id) { $sql = "DELETE FROM users WHERE id = :id"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $id); return $stmt->execute(); } }
Create entry point (index.php)
<?php namespace Controllers; use Models\User; class UserController { public function createUser($name, $email) { $user = new User(); return $user->create($name, $email); } public function getUsers() { $user = new User(); return $user->read(); } public function updateUser($id, $name, $email) { $user = new User(); return $user->update($id, $name, $email); } public function deleteUser($id) { $user = new User(); return $user->delete($id); } }
Summary
By following OOP principles and applying best practices in PHP, we built a simple and scalable CRUD application. This approach allows you to easily extend your project with new functionality or improve database interaction.
In this guide, we cover:
- Simple and easy to maintain folder structure.
- Reusable Database class for MySQL connections.
- User model that encapsulates all CRUD operations.
- UserController for handling business logic.
This structure makes your PHP applications cleaner, more modular, and easier to extend. You can now use this approach to build larger, more complex applications using OOP and MySQL.
Happy coding! ?
The above is the detailed content of Building a PHP CRUD Application with OOP and MySQL: A Best Practice Guide. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

To view the size of the MySQL database and table, you can query the information_schema directly or use the command line tool. 1. Check the entire database size: Execute the SQL statement SELECTtable_schemaAS'Database',SUM(data_length index_length)/1024/1024AS'Size(MB)'FROMinformation_schema.tablesGROUPBYtable_schema; you can get the total size of all databases, or add WHERE conditions to limit the specific database; 2. Check the single table size: use SELECTta

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

The most direct way to connect to MySQL database is to use the command line client. First enter the mysql-u username -p and enter the password correctly to enter the interactive interface; if you connect to the remote database, you need to add the -h parameter to specify the host address. Secondly, you can directly switch to a specific database or execute SQL files when logging in, such as mysql-u username-p database name or mysql-u username-p database name

The setting of character sets and collation rules in MySQL is crucial, affecting data storage, query efficiency and consistency. First, the character set determines the storable character range, such as utf8mb4 supports Chinese and emojis; the sorting rules control the character comparison method, such as utf8mb4_unicode_ci is case-sensitive, and utf8mb4_bin is binary comparison. Secondly, the character set can be set at multiple levels of server, database, table, and column. It is recommended to use utf8mb4 and utf8mb4_unicode_ci in a unified manner to avoid conflicts. Furthermore, the garbled code problem is often caused by inconsistent character sets of connections, storage or program terminals, and needs to be checked layer by layer and set uniformly. In addition, character sets should be specified when exporting and importing to prevent conversion errors
