如何在Laravel中建立数据库连接?

时间:2017-02-15 06:13:51

标签: php laravel database-connection

这是我在纯PHP中的代码:

$dbh = new PDO('mysql:host=localhost;dbname=dbName', 'root', '');

在Laravel中它的等同物是什么?

注意到,这些都不起作用:

$dbh = DB::connection('dbName');

$dbh = DB::connection('dbName')->getPdo();

修改

这是我的代码:(它不起作用)

// /config/database.php

'connections' => [
    'myconn' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'dbName'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],
]



// app/files/test.php

$dbh = DB::connection()->getPdo();
$sth = $dbh->query("SELECT * FROM mytable");
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

这是工作版本:

// app/files/test.php
$dbh = new PDO('mysql:host=localhost;dbname=dbName', 'root', '');
$sth = $dbh->query("SELECT * FROM mytable");
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

2 个答案:

答案 0 :(得分:1)

试试这个

static function db ()
        {
            try {
                $db = DB::connection()->getPdo();
            }
            catch (PDOException $e) {
                self::fatal(
                    "An error occurred while connecting to the database. ".
                    "The error reported by the server was: ".$e->getMessage()
                );
            }
            return $db;
        }

通过调用..

$db=self::db();

$db::PARAM_STR

参考laravel DB::connection()->getPdo()::PARAM_STR not working

答案 1 :(得分:-1)

试试这个。

    'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
],