laravel DB::Table 和 DB::Select 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28298954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between DB::Table and DB::Select
提问by Loko
At the moment I am using:
目前我正在使用:
DB::select('select * from users ');
but now I'm reading on http://laravel.com/docs/4.2/queries
但现在我正在阅读http://laravel.com/docs/4.2/queries
about:
关于:
$users = DB::table('users')->get();
Both give back the same. Is there something different between these two?
两者都回馈相同。这两者之间有什么不同吗?
In the documentation it does say: Note: The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
在文档中它确实说: Note: The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
For the second method. Does this mean the first method doesn't protect you against SQL injection? Is the second method a better way? Both return the results in a different way as well right?
对于第二种方法。这是否意味着第一种方法不能保护您免受 SQL 注入?第二种方法是不是更好的方法?两者都以不同的方式返回结果,对吗?
Can I get some explanation about this?
我能得到一些关于这个的解释吗?
采纳答案by lukasgeiter
No, the only difference here is the syntax. Yes, a DB::select
doesn't protect against SQL injection. But SQL injection is only a risk when you pass in user input. For example this is vulnerable to SQL injection:
不,这里唯一的区别是语法。是的,aDB::select
不能防止 SQL 注入。但是 SQL 注入只有在您传入用户输入时才有风险。例如,这很容易受到 SQL 注入的攻击:
DB::select('SELECT * FROM users WHERE name = "'.Input::get('name').'"');
Whereas this is not:
而这不是:
DB::table('users')->where('name', Input::get('name'))->get();
But also this isn't: (Using bindings "manually")
但这也不是:(“手动”使用绑定)
DB::select('SELECT * FROM users WHERE name = ?', array(Input::get('name')));
The great advantage of the query builder (besides automatically protecting against SQL injection) is it's flexible syntax. For example you could use a loop to add where
statements:
查询构建器的一大优势(除了自动防止 SQL 注入)是它灵活的语法。例如,您可以使用循环添加where
语句:
$query = DB::table('users');
foreach($names as $name){
$query->orWhere('name', 'LIKE', $name.'%');
}
$result = $query->get();