1.修改配置文件/.nev
DB_HOST=127.0.0.1 //数据库地址 DB_PORT=3306 //数据库端口 DB_DATABASE=database //数据库名称 DB_USERNAME=root //数据库账号 DB_PASSWORD=root //数据库密码
2.开始测试是否连接成功
/App/Http/routes.php 路由代码如下(可以自定义)
Route::get(‘dbtest‘,‘Admin\[email protected]‘);
3.新建IndexController控制器
/App/Http/Controllers/IndexController 控制器代码如下(可以自定义)
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; class IndexController extends Controller{ public function dbcc(){ $pdo=DB::connection()->getPdo(); dd($pdo); } }
4.浏览访问测试
浏览器访问http://127.0.0.1/index.php/dbtest 成功提示如下图
PDO {#123 ▼ inTransaction: false attributes: {▼ CASE: NATURAL ERRMODE: EXCEPTION AUTOCOMMIT: 1 PERSISTENT: false DRIVER_NAME: "mysql" SERVER_INFO: "Uptime: 3026 Threads: 4 Questions: 476 Slow queries: 0 Opens: 42 Flush tables: 1 Open tables: 1 Queries per second avg: 0.157" ORACLE_NULLS: NATURAL CLIENT_VERSION: "mysqlnd 5.0.11-dev - 20120503 - $Id: f373ea5dd5538761406a8022a4b8a374418b240e $" SERVER_VERSION: "5.5.40" STATEMENT_CLASS: array:1 [] CONNECTION_STATUS: "127.0.0.1 via TCP/IP" DEFAULT_FETCH_MODE: BOTH }}
遇到常见问题;
1.如果你的数据库表有前缀怎么处理
1.1/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‘, ‘strict‘ => false, ‘engine‘ => null, ],
1.2修改成如下代码
‘mysql‘ => [ ‘driver‘ => ‘mysql‘, ‘host‘ => env(‘DB_HOST‘, ‘localhost‘), ‘port‘ => env(‘DB_PORT‘, ‘3306‘), ‘database‘ => env(‘DB_DATABASE‘, ‘forge‘), ‘username‘ => env(‘DB_USERNAME‘, ‘forge‘), ‘password‘ => env(‘DB_PASSWORD‘, ‘‘), ‘prefix‘ => env(‘DB_PREFIX‘, ‘‘), ‘charset‘ => ‘utf8‘, ‘collation‘ => ‘utf8_unicode_ci‘, ‘strict‘ => false, ‘engine‘ => null, ],
1.3配置文件/.nev修改成如下代码
DB_HOST=127.0.0.1 //数据库地址 DB_PORT=3306 //数据库端口 DB_DATABASE=database //数据库名称 DB_PREFIX=unics_ //数据库表前缀名称 DB_USERNAME=root //数据库账号 DB_PASSWORD=root //数据库密码
时间: 2024-10-10 16:37:50