search
HomePHP FrameworkLaravelUse Laravel Eloquent queries alone in your PHP project to avoid SQL injection

OWASP (Open Web Application Security Project) is a project that records the current threats to web applications. I have been following their site and I see some similarities in the reports from 2010, 2013 and 2017, with SQL or other types of injection threats at the top of the list.

This is a serious problem.

It will cause you to go bankrupt, so this matter is related to life and death, and your organization should focus on dealing with this type of problem to avoid its occurrence.

What is injection?

The so-called injection means that the data is not filtered and untrustworthy content is written directly into the system interpreter. This behavior will lead to SQL injection into the site. What's worse, the attacker may will gain full permissions on the system.

For example:

Look at the following malicious query statement. It will put the SQL statement containing malicious behavior in the $name variable, and then allow the user to pass POST method is passed to the PHP script, so as to achieve the ultimate purpose of using the incoming malicious code to carry out attacks.

// 将恶意代码,DROP TABLE 写入 $name 变量
$name = "Mark';DROP TABLE users; -- ";\ $query = "SELECT * FROM users WHERE name='$name'";

After parsing by the PHP script, this will eventually generate a SQL statement like this:

SELECT * FROM users WHERE name='Mark';DROP TABLE users; -- '

As you might guess, the above statement will delete the entire users data table from the database.

As Yoda said:

This is too dangerous, yes, too dangerous.

How to prevent malicious injection into PHP applications?

First of all, nothing is actually injected into the database. This error is just due to the incorrect formatting of the query statement. The solution is simple, as long as you format the SQL statement correctly, or directly process the query statement and data separately.

How to do it? Use parameterized queries to format data and separate query statements from data.

Using parameterized queries can ensure that the program is away from injection risks.

Examples are as follows:

$statement = $db->prepare('SELECT * FROM table WHERE id = ? and name = ? ');\ $statement->execute([1, "Mark"]);

In addition, there is a safe way to use ORM (Object Relational Mapping) or query builder in the project.

What I want to recommend is Eloquent, which is also used by the famous PHP framework Laravel. Next, I will teach you how to install and use it, which can help us format data to effectively avoid injection hazards.

Installing Eloquent

Preparation

Please make sure you have installed PHP and Composer.

Official start

It is best to install the ORM at the beginning of the project.

Suppose we want to build a blog application, including a posts table and a users table.

Initialization configuration

The first thing to do is to create the composer.json file for the program. You can run composer init on the terminal and follow the prompts on the terminal.

Use Laravel Eloquent queries alone in your PHP project to avoid SQL injection

#When it asks you to define dependencies, write illuminate/database . The final output should look like the one shown in the image above. Now you can install the corresponding dependencies in the project by running composer install .

Or, if you already have the composer.json file, you can directly enter composer require illuminate/database in the terminal to install the corresponding dependencies.

Now we need to create the start.php file in the root directory of the application and paste the following code into the file. I'll explain their role below.

require "vendor/autoload.php";
//If you want the errors to be shown  *是否显示错误
error_reporting(E_ALL);
ini_set('display_errors', '1');
use Illuminate\Database\Capsule\Manager as Capsule;
 $capsule = new Capsule;
 $capsule->addConnection([
    "driver" => "mysql",
    "host" =>"127.0.0.1",
    "database" => "test",
    "username" => "root",
    "password" => "root"
 ]);
//Make this Capsule instance available globally. *要让 capsule 能在全局使用
 $capsule->setAsGlobal();
// Setup the Eloquent ORM.
 $capsule->bootEloquent();

In the first line we need to introduce the vendor/autoload.php file. In this way we can load all packages in the vendor directory.

Then we introduce use Illuminate\Database\Capsule\Manager as Capsule and give it an alias so that we can use eloquent.

Next, we create a Capsule object and initialize our database connection, as above bootEloquent().

Now, obviously the first thing we need to do is create a database named test. Please make sure you enter the correct username and password locally.

Migrations / Data Migration

One of the biggest benefits of using Eloquent is that you can use migrations.

If you don’t understand what migrations are, you can read the explanation below:

Migration is a way to create data tables through PHP code.

Create migration in the migrations.php file:

require "start.php";
use Illuminate\Database\Capsule\Manager as Capsule;
Capsule::schema()->create('users', function ($table) {
   $table->increments('id');
   $table->string('name');
   $table->string('email')->unique();
   $table->string('password');
   $table->timestamps();
});
Capsule::schema()->create('posts', function ($table) {
   $table->increments('id');
   $table->string('title');
   $table->text('body');
   $table->integer('created_by')->unsigned();
   $table->timestamps();
});

The above code creates two data tables through the Capsule class, one is the users table and the other is the posts table, and respectively Field names are defined for them.

Run this file. If you see a white screen, it means that migrations has been run successfully. Now you can open the database to see if these two tables have been generated.

Use Laravel Eloquent queries alone in your PHP project to avoid SQL injection

Models

Now, the only thing to do is to create the Model class corresponding to the data table.

用了 Eloquent,你就可以在 Model 类里操作相应的数据表,执行查询语句了。

创建一个 Models 文件夹,然后在其中分别创建 User.php 和 Post.php 文件:

namespace Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
   /**
    * 对应的数据表
    *
    * @var string
    */
    protected $table = "users";
   /**
    * 允许插入的字段
    *
    * @var array
    */
    protected $fillable = [
        'name', 'email', 'password'
    ];
   /**
    * 需要被隐藏的字段
    *
    * @var array
    */
    protected $hidden = [
        'password', 'remember_token',
    ];
   /*
    * 给 User 类添加方法
    *
    */
    public function posts()
    {
        return $this->hasMany(Post::class, 'created_by');
    }
}
And
namespace Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
   /**
    * 对应的数据表
    *
    * @var string
    */
    protected $table = "posts";
  /**
   * 允许插入的字段
   *
   * @var array
   */
   protected $fillable = [
       'title', 'body', 'created_by'
   ];
 }
在 composer.json 文件中加入如下代码,以确保上面创建的类文件能够被自动加载。
"autoload": {
    "classmap": [
        "Models" // Folder where all your models are
     ]
}

然后执行 composer dump-autoload。

通过 Eloquent 操作数据库

基本大功告成了。 测一下吧,在根目录创建 index.php 文件,添加如下代码:

require "start.php";
use Models\User;
use Models\Post;
User::create(
 [
  'name' => 'Mark Mike',
  'email' => 'temp-email-1@mark.com',
  'password' => '1234'
 ]
);
Post::create(
 [
  'title' => 'New Blog Post',
  'body' => 'New Blog Content',
  'created_by' => 1
 ]
);
print_r(User::all());
print_r(Post::all());
print_r(User::find(1)->posts);

如你所见,用 Eloquent 操作数据库就是这么简单。除此之外,Eloquent 还提供了很多方法供你使用,而且很安全。

结语:

Eloquent 就像是给你的 SQL 查询加了一道安全层,它可以过滤掉我们在执行 SQL 查询时所犯的错误。如果你想用它,但是又不想安装 Laravel 框架,那么我想你已经从这篇文章中学到了该如何去做。这个优雅的 SQL 助手,将帮助你写出更干净且更安全的代码。

更多PHP相关知识,请访问PHP中文网

The above is the detailed content of Use Laravel Eloquent queries alone in your PHP project to avoid SQL injection. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel in Action: Real-World Applications and ExamplesLaravel in Action: Real-World Applications and ExamplesApr 16, 2025 am 12:02 AM

Laravelcanbeeffectivelyusedinreal-worldapplicationsforbuildingscalablewebsolutions.1)ItsimplifiesCRUDoperationsinRESTfulAPIsusingEloquentORM.2)Laravel'secosystem,includingtoolslikeNova,enhancesdevelopment.3)Itaddressesperformancewithcachingsystems,en

Laravel's Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),