Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DB::Table and DB::Select

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?

like image 463
Loko Avatar asked Feb 03 '15 12:02

Loko


People also ask

What is the difference between a table and a view SQL?

View and Table both are integral parts of a relational database, and both terms are used interchangeably. The view is a result of an SQL query and it is a virtual table, whereas a Table is formed up of rows and columns that store the information of any object and be used to retrieve that data whenever required.

How do you select data in a database?

An SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria. The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value';

What is the difference between table and view in SAP?

A table consists of rows and columns to store and organized data in a structured format, while the view is a result set of SQL statements. A table is structured with columns and rows, while a view is a virtual table extracted from a database.

What is a table view in database?

A view is a virtual table whose contents are defined by a query. Like a table, a view consists of a set of named columns and rows of data. Unless indexed, a view does not exist as a stored set of data values in a database.


1 Answers

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();
like image 172
lukasgeiter Avatar answered Sep 30 '22 15:09

lukasgeiter