本文转自:https://fideloper.com/laravel-raw-queries

Business logic is often complicated. Because of this, we often need to write our own SQL queries. Luckily, Laravel's query builder has the tools we need to safely run such queries.

A key concern when writing our own queries is protecting our application from SQL injection attacks. Normally, the query builder does this for us. However, when we write our own SQL, we need to make sure we don't inadvertently remove this protection.

Here's what we want to avoid:

$someVariable = Input::get("some_variable");

$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'") );

In the above query, we're directly adding user input into the query without sanitizing it. This leaves us open to attack!

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.

Since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.

Now, as you've seen, arbitrary (raw) queries are done in the query builder using the DB::select() method. Let's look at the select() method in Illuminate\Database\Connection to see if it has any way to bind our parameters:

public function select($query, $bindings = array())
{
return $this->run($query, $bindings, function($me, $query, $bindings)
{
if ($me->pretending()) return array(); // For select statements, we'll simply execute the query and return an array
// of the database result set. Each element in the array will be a single
// row from the database table, and will either be an array or objects.
$statement = $me->getPdo()->prepare($query); $statement->execute($me->prepareBindings($bindings)); return $statement->fetchAll($me->getFetchMode());
});
}

Perfect! We see above that we can pass an array of bindings to the select()method. This array is bound to the query via the PDO connection.

We can, therefore, change our previous query in a way that sanitizes the user input:

$someVariable = Input::get("some_variable");

$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array(
'somevariable' => $someVariable,
));

Voìla! Safe queries!

Lastly, if you are performing queries which don't return data, then using a SELECT query will result in errors. For example, if you want to start the auto-increment ID of a MySQL table to something other than zero, we can use the statement method. With statement, we don't need to use the raw() method:

// Warning: This is a MySQL-specific query
DB::statement( 'ALTER TABLE HS_Request AUTO_INCREMENT=9999' );

The statement method can also accept parameters:

DB::statement( 'ALTER TABLE HS_Request AUTO_INCREMENT=:incrementStart', array('incrementStart' => 9999) );

[转]Raw Queries in Laravel的更多相关文章

  1. Executing Raw SQL Queries using Entity Framework

    原文 Executing Raw SQL Queries using Entity Framework While working with Entity Framework developers m ...

  2. laravel 配置MySQL读写分离

    前言:说到应对大流量.高并发的解决方案的时候,总会有这样的回答,如:读写分离,主从复制...等,数据库层今天先不讨论,那么今天我们就来看看怎么在应用层实现读写分离. 框架:laravel5.7(所有配 ...

  3. Sequelize-nodejs-11-Raw queries

    Raw queries原始查询 就是使用了原始的查询语句,如UPDATE users SET y = 42 WHERE x = 12 As there are often use cases in w ...

  4. laravel3中文文档是迈入laravel4的捷径

    http://v3.golaravel.com/docs/ 目录 Laravel概览 更新日志 安装与设置 系统需求 安装 服务器设置 基本设置 环境 友好的链接(URL) 路由 基础 通配符(Wil ...

  5. Laravel5.1学习笔记16 数据库2 查询构造器(这个不用看,不如用EloquentORM)

    Introduction Retrieving Results Aggregates Selects Joins Unions Where Clauses Advanced Where Clauses ...

  6. Laravel5.1学习笔记15 数据库1 数据库使用入门

    简介 运行原生SQL查询  监听查询事件 数据库事务 使用多数据库连接 简介 Laravel makes connecting with databases and running queries e ...

  7. code_action

    w https://raw.githubusercontent.com/laravel/laravel/master/config/database.php <?php return [ /* ...

  8. Python札记 -- MongoDB模糊查询

    最近在使用MongoDB的时候,遇到了使用多个关键词进行模糊查询的场景.竹风使用的是mongoengine库. 查了各种资料,最后总结出比较好用的方法.先上代码,后面进行详细说明.如下: #!/usr ...

  9. 【转】一个lucene的官网例子

    创建索引: import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import jav ...

随机推荐

  1. 安装virtualbox出现2503、2502的错误提示解决方法

    安装virtualbox右键选择以管理员的身份打开即可

  2. python基础自学 第一天

    python的概述 python的创始人:吉多·范罗苏姆 1991年,第一个python解释器诞生,用C语言实现,并能调用C语音的库文件 解释器(解释型语言和编 译型语言的区别) 把其他语言翻译成计算 ...

  3. TeeChart For VCL/FMX V2017使用教程:第一章-准备开始

    https://blog.csdn.net/vbfgm/article/details/79338775 第一章 准备开始-构建图表和填充数据序列 1.1 简介 通过代码或Dataset(数据集)访问 ...

  4. 了解iOS消息推送一文就够:史上最全iOS Push技术详解

    本文作者:陈裕发, 腾讯系统测试工程师,由腾讯WeTest整理发表. 1.引言 开发iOS系统中的Push推送,通常有以下3种情况: 1)在线Push:比如QQ.微信等IM界面处于前台时,聊天消息和指 ...

  5. Java工程师必备

    Java工程师必备 JAVA基础扎实,熟悉JVM,熟悉网络.多线程.分布式编程及性能调优 精通Java EE相关技术 熟练运用Spring/SpringBoot/MyBatis等基础框架 熟悉分布式系 ...

  6. Day9:html和css

    Day9:html和css <head> <meta charset="UTF-8"> <title></title> <me ...

  7. 从前端中的IOC理念理解koa中的app.use()

    忙里偷闲,打开平时关注的前端相关的网站,浏览最近最新的前端动态.佼佼者,平凡的我做不到,但还是要争取不做落后者. 前端中的IoC理念,看到这个标题就被吸引了.IoC 理念,不认识呢,点击去一看,果然没 ...

  8. centos上ftp服务器的简易安装部署

    申明:本示例为centos7 开启ftp服务命令为:systemctl start vsftpd 关闭防火墙命令为systemctl stop firewalld 7版本以下开启ftp服务器为 ser ...

  9. 学习关于display :flex 布局问题!

    很多人不明白这个display:flex是到底是什么东西,如何使用的  . 1.什么是display:flex呢? 答:flex是 flexible  box的缩写,意为弹性布局 :这个东西的引入,为 ...

  10. Hystrix 停止开发。。。Spring Cloud 何去何从?

    栈长得到消息,Hystrix 停止开发了... 大家如果有对 Hystrix 不清楚的,请看下这篇文章:分布式服务防雪崩熔断器,Hystrix理论+实战. 来看下 Hystrix 停止开发官宣: ht ...