I cannot access the raw PDO instance in Laravel 5

2020-04-21 07:20发布

问题:

I'm new to laravel and I'm trying to access the raw PDO instance referring to this doc http://laravel.com/docs/5.0/database#accessing-connections by using this code DB::connection()->getPdo(); to my controller. But I'm getting this error:

FatalErrorException in GeneralCategoryController.php line 24:
Class 'App\Http\Controllers\DB' not found

I've already tried to include this namespace Illuminate\Support\Facades\DB but still no result. Please note that I'm connected already to mysql database. Am I missing something?

回答1:

$pdo = DB::connection()->getPdo();
$query=$pdo->prepare("SHOW TABLES");
$query->execute();//$query->execute(array($bindings ));
while($row=$query->fetch(\PDO::FETCH_BOTH)) {
    //Use \PDO::FETCH_ASSOC, \PDO::FETCH_OBJ    
    //echo $row->yourcolumnname;//its an object when \PDO::FETCH_OBJ
    echo $row[0]; //Indexed Array

}


回答2:

You need either to reference it as \DB or add a use DB; at the top of your controller.