laravel框架数据库配置及操作数据库示例

laravel 数据库配置

数据库配置文件为项目根目录下的config/database.php

//默认数据库为mysql 'default' => env('DB_CONNECTION', 'mysql'), 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],

发现都在调用env函数,找到env文件,即根目录下的.env文件,

打开修改配置参数

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret

修改为本地的数据库信息:

DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=123456

laravel 操作数据库

建立student控制器,控制器代码

namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; class StudentController extends Controller { //添加 public function addstudent(){ $student = DB::insert('insert into student(name,age,gender) values(?,?,?)',['张三',12,2]); var_dump($student);//成功返回bloo值true } //获取 public function getall(){ // $student = DB::select('select * from student'); $student = DB::select('select * from student where id>?',[1]); return $student;//数组 } //修改 public function updstudent(){ $student = DB::update('update student set age= ? where name=?',[10,'张三']); var_dump($student);//成功返回bloo值true } //修改 public function delstudent(){ $student = DB::delete('delete from student where id=?',[10]); var_dump($student); } }

注意 laravel中return true会报错:

(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "boolean" given.

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/e6cc1d19d447a7e7c949d8f91b42ad17.html