1. 新建数据库表与连接数据库
1.1. 新建数据库表
/*
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` tinyint(4) DEFAULT '0',
`sex` tinyint(4) DEFAULT '10',
`created_at` int(11) DEFAULT '0',
`updated_at` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8;
1.2. 连接数据库
连接信息保存在 config/database.php
文件和 .env
文件
修改 .env
文件
DB_HOST=127.0.0.1
DB_DATABASE=root
DB_USERNAME=''
DB_PASSWORD=secret
修改 config/database.php
文件
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
]
2. CURD操作
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{
public function test1()
{
// 选择
$student = DB::select('SELECT * FROM student');
var_dump($student); // 返回一个数组
// 插入
$bool = DB::insert('INSERT INTO student(name, age) VALUES(?, ?)', [
'Rebecca Liu', 19
]);
var_dump($bool); // 返回是否插入成功
$student = DB::select('SELECT * FROM student');
var_dump($student);
// 更新
$qty = DB::update('UPDATE student SET age = ? WHERE id = ?', [
22, 1002
]);
var_dump($qty); // 返回更新的行数
// 删除
$qty = DB::delete('DELETE FROM student WHERE id = ?', [1002]);\
var_dump($qty); // 返回删除的行数
}
}