首先设置数据库
- 找到数据库文件 .env
第9行到14行
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=php
DB_USERNAME=root
DB_PASSWORD=123456
修改成自己的数据库账户
创建控制器 Home.php
- 在app/Http/Controllers 目录下创建控制器
- 可以用命令行的方式创建 也可以新建文件的方式创建
控制器代码:
<?php
namespace App\Http\Controllers;
use DB;
class Home extends Controller{
// 数据库查询
public function get(){
echo '<pre>';
$res = DB::select('select * from users');
print_r($res);
}
//数据库更新
public function gxupdata(){
$res = DB::update('update users set name="我知道,最好的语言:php25岁了" where id=4');
var_dump($res);
}
//数据库新增
public function xzupdata(){
$res = DB::insert('insert users(`name`,`email`,`password`)values("mignzi","ad@s.com","aginogsg")');
var_dump($res);
}
//删除数据
public function delete(){
$res = DB::delete("delete from users where id=2");
var_dump($res);
}
public function index(){
// 加载v视图文件
$res = DB::select('SELECT * FROM `jizhang`');
$lists = [];
foreach ($res as $val){
$lists[] = (array)$val;
}
$data['result'] = $lists;
// print_r($val);
return view('v', $data);
}
}
设置路由
- 路径public/routes/web.php
路由代码:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('v');
// echo date('Y-m-d h:i:s');
});
Route::get('/article/p/aaa', function () {
// return view('v');
echo date('Y-m-d h:i:s');
});
Route::get('home/index','Home@index');
Route::get('/db','Home@get');
Route::get('/dbgx','Home@gxupdata');
Route::get('/dbxz','Home@zxupdata');
Route::get('/dbsc','Home@delete');
添加视图文件
- 路径public/resources/views/v.blade.php
文件代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数据库操作</title>
<link rel="stylesheet" type="text/css" href="/layui/css/layui.css">
<script src="layui/layui.js"></script>
</head>
<body>
<table class="layui-table">
<thead>
<tr>
<td>ID</td>
<td>金额</td>
<td>账户</td>
<td>成员</td>
<td>备注</td>
<td>成员id</td>
</tr>
</thead>
<tbody>
<?php foreach ($result as $val): ?>
<tr>
<td><?php echo $val['id']; ?></td>
<td><?php echo $val['jine']; ?></td>
<td><?php echo $val['zhanghu']; ?></td>
<td><?php echo $val['chengyuan']; ?></td>
<td><?php echo $val['beizhu']; ?></td>
<td><?php echo $val['yonghuid']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
效果:
总结:本节课学习了 laravel框架 的mvc 与数据库查询删除修改的操作,更详细了学习了laravel框架。