laravel自定义数据库驱动
laravel框架数据库配置及操作数据库示例本文实例讲述了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框架的PHP程序设计有所帮助。
原文链接:https://www.cnblogs.com/gyfluck/p/9037337.html