Laravel查询构造器(query builder)提供方便、流畅的接口,用来建立执行数据库查找语法;
使用PDO参数绑定,以保护应用程序免于SQL注入因此传入的参数不需要额外转义特殊字符;
基本可以满足所有的数据库操作,而且在所有支持的数据库系统上都可以执行。
程序运行截图如下:
对应的表结构是这样的:
/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.12 : Database - laravel
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`laravel` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
USE `laravel`;
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*Data for the table `student` */
insert into `student`(`id`,`name`,`age`) values (2,'小张',19),(3,'小明',18),(4,'小张',19);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
源码如下:
路由web.php添加:
Route::prefix('student')->group(function(){
Route::get('dbFacadeInsert', 'StudentController@dbFacadeInsert');
Route::get('dbFacadeSelect', 'StudentController@dbFacadeSelect');
Route::get('dbFacadeModify', 'StudentController@dbFacadeModify');
Route::get('dbFacadeDelete', 'StudentController@dbFacadeDelete');
});
这个config/database.php是数据库相关的设置,目前不用改,对应mysql是这样的。
需要修改的是
.env
修改为如下:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root
新建StudentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller{
public function dbFacadeSelect(){
$students = DB::select('select * from student');
var_dump($students);
return "dbFacadeSelect";
}
public function dbFacadeInsert(){
$bool = DB::insert('insert into student(name, age) value(?, ?)', ['小明', 18]);
$bool = DB::insert('insert into student(name, age) value(?, ?)', ['小张', 19]);
return "dbFacadeInsert";
}
public function dbFacadeModify(){
$num = DB::update('update student set age = ? where name = ?', [20, '小明']);
//var_dump($num);
return "dbFacadeInsert";
}
public function dbFacadeDelete(){
$num = DB::delete('delete from student where id = ?', [1]);
var_dump($num);
return "dbFacadeDelete";
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://it1995.blog.csdn.net/article/details/124723869
内容来源于网络,如有侵权,请联系作者删除!