Laravel 执行原生 sql

一、Laravel 执行原生 sql

1 插入数据

DB::insert('insert into test (id, name, email, password) values (?, ?, ? , ? )',[1, 'Laravel','[email protected]','Laravel']);

2 查询语句

$user = DB::select('select * from test where id = ?', [1]);

我们还 可以看到在执行查询的时候使用了参数绑定,以避免SQL注入。除此之//外还可以使用命名绑定:

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

示例一

$info = DB::select('select * from chat_communication where (fromid=:fromid && toid=:toid) || (fromid =:fromid2 && toid=:toid2)', ['fromid'=>$fromid,'toid'=>$toid,'fromid2'=>$toid,'toid2'=>$fromid]);
dd($info);

在这里插入图片描述

3 更新语句

$resule = DB::update('update test set name="laraveltest" where name = ?', ['laravel']);
 
//此处返回值为影响的行数请注意,不能直接做判断的
if($resule || $resule===0){
    
    
    //成功的提示语
     return true;
}else{
    
    
   //失败的提示语
    return false;
}

4 删除语句

$deleted = DB::delete('delete from test');

猜你喜欢

转载自blog.csdn.net/weiguang102/article/details/125081221