Current Location: Home> Latest Articles> ThinkPHP5 Data Insertion Explained: Examples Using ORM and SQL

ThinkPHP5 Data Insertion Explained: Examples Using ORM and SQL

gitbox 2025-07-18

Introduction

When developing with the ThinkPHP5 framework, adding data is a very common operation. This article explains the specific methods for inserting data in ThinkPHP5 through examples, showing how to use both ORM models and raw SQL statements for data insertion.

Adding Data Using ORM

Defining a Model

Before adding data using the ORM approach, you need to create a model corresponding to the database table. ThinkPHP5 supports quickly generating model files via the command line, for example:

php think make:model User

This command will generate a model file named User in the app/model directory. The model file by default includes the corresponding table name, primary key, and field validation rules.

Inserting Data

In a controller, you can instantiate the model object and call the save() method to add data. For example, to insert a record into the users table:

$user = new User;
$user->name = 'John';
$user->age = 25;
$user->save();

The code above creates a User model object, assigns values, and calls the save() method to save the data.

Additionally, you can combine the validate() method for data validation to ensure data integrity:

$user->validate(true)->save();

Adding Data Using SQL Statements

Besides the ORM approach, ThinkPHP5 also supports inserting data using raw SQL statements. You can use the Db class's execute() method to run SQL commands:

use think\Db;
<p>Db::execute("INSERT INTO <code>users

This method directly executes the SQL statement, inserting data into the users table.

Preventing SQL Injection

When executing raw SQL, preventing SQL injection is crucial. It is recommended to use parameter binding to pass data safely and avoid security risks:

$name = 'John';
$age = 25;
<p>Db::execute("INSERT INTO <code>users

Parameter binding ensures that the inserted data is not interpreted as SQL code, enhancing security.

Conclusion

This article provides a detailed introduction to two common methods for inserting data in ThinkPHP5. Using ORM models is convenient and fast, suitable for most applications; raw SQL offers greater flexibility but requires careful attention to prevent SQL injection. Choosing the appropriate method based on actual needs helps efficiently complete data insertion operations.