Run native SQL queries

Once the database connection is configured, you can run the query using the DB object. DB provides methods for each type of query: select, selectOne, update, insert, delete, cursor, statement, affectingStatement, and unprepared.

Run the query statement

  $users = DB::select('select * from `user` where `status` = ?', [1]);   

select method will always return an array, and each result in the array is an = Array , which can be accessed like this:

 foreach ($users as $user) {
    echo $user->name;

If just querying an available selectOne result returns an = Array , if there is no query to return the data is an empty Array .

     $sql= 'select * from `user` where `id` = ?';
    $res = DB::selectOne($sql, [1]);
    if ($res) {
        echo $res->name;

If you are the fastest way to traverse the data table all the data is available using the DB::cursor($sql) method

     $sql= 'select * from `user`';
    $res = DB::cursor($sql);
    foreach($res as $user){
       echo $user->name;

Why is it the fastest, because the bottom layer uses the yield mechanism to get data much faster than the chunk

Use named binding

In addition to using ? indicate parameter binding, you can also use a named binding to execute a query:

 $results = DB::select('select * from `user` where `id` = :id', ['id' => 1]); 

Run the insert statement

You can use the insert method of DB Facade to execute an insert statement. Like select, this method takes the native SQL query as its first argument and binds the data as the second argument:

 DB::insert('insert into users (`id`, `name`) values (?, ?)', [1, 'sumi']); 

Run the update statement

The update method is used to update existing records in the database. This method returns the number of rows affected by the statement:

 $affected = DB::update('update `user` set `status` = 2 where `name` = ?', ['ovo']); 

Run the delete statement

The delete method is used to delete records from the database. Like update, returns the number of rows affected by this statement:

 $deleted = DB::delete('delete from `users`'); 

Running ordinary statements

Some database statements do not have any return value. For these statements, you can use DB's statement method to run:

 DB::statement('drop table `user`'); 

Some database statements if you want to know if the execution is successful. For these statements, you can use DB's unprepared method to run:

 $unprepared = DB::unprepared('DROP TRIGGER IF EXISTS `sync_to_item_table`');
if ($unprepared) {
    // Todo something...

Only use unprepared method to execute multiple sql, need to pre-process can not execute multiple sql