Difference between DB::Table and DB::Select

22,953

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:

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:

$query = DB::table('users');

foreach($names as $name){
    $query->orWhere('name', 'LIKE', $name.'%');
}

$result = $query->get();
Share:
22,953
Loko
Author by

Loko

26 years old top 5% of php top 10% of mysql and html top 20% of laravel http://data.stackexchange.com/stackoverflow/query/52751/tag-rankings Software Developer September 2019 - Currently Software developer - Laravellaravel Reactjsreactjs Magentomagento Wordpresswordpress NextJSnextjs Typescripttypescript Sasssass November 2016 - August 2019 Software developer - PHPphp April 2016 - October 2016 Junior PHP Developer - PHPphp Symfonysymfony July 2015 - September 2015 Software developer - Laravellaravel PHPphp Finished school and got a degree in software engineering in June 2015 January 2015 - June 2015 Intern - Laravellaravel PHPphp June 2013 - January 2014 Intern - C#c# Oracleoracle GISgis PHP CSS HTML MYSQL Javascript Basic Linux Very little Gis and Oracle experience

Updated on July 09, 2022

Comments

  • Loko
    Loko almost 2 years

    At the moment I am using:

    DB::select('select * from users ');
    

    but now I'm reading on 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.

    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?

    Can I get some explanation about this?