如何在 PHP 和 Laravel 中测试 MySQL 连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24190647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:12:24  来源:igfitidea点击:

How to test MySQL connection in PHP and Laravel?

phpmysqllaravellaravel-4

提问by mpet

I'm making a PHP application installer (something like Wordpress installation script) and I need to check mysql connection using host name, username, password and database provided by user during installation.

我正在制作一个 PHP 应用程序安装程序(类似于 Wordpress 安装脚本),我需要使用安装过程中用户提供的主机名、用户名、密码和数据库来检查 mysql 连接。

I'm using this code as a Laravel controller method to test connection:

我将此代码用作 Laravel 控制器方法来测试连接:

public function TestDatabaseConnection(){
    try {
        $database_host = Config::get('config.database_host');
        $database_name = Config::get('config.database_name');
        $database_user = Config::get('config.database_user');
        $database_password = Config::get('config.database_password');

        $connection = mysqli_connect($database_host,$database_user,$database_password,$database_name);

        if (mysqli_connect_errno()){
                return false;
            } else {
                return true;
            }

    } catch (Exception $e) {

        return false;

    }
}

This code doesn't seem to properly test the connection. Function return value (true/false) doesn't depend whether user supplies db data at all, or if db data is correct/incorrect..

此代码似乎没有正确测试连接。函数返回值(真/假)不取决于用户是否提供数据库数据,或者数据库数据是否正确/不正确。

Fils /app/config/config.php contains the following array:

Fils /app/config/config.php 包含以下数组:

<?php return array('database_host' => 'localhost', 'database_name' => 'dbasename',    'database_user' => 'dbuser', 'database_password' => 'pass');

and it's being updated via form during installation process.

并且在安装过程中通过表单进行更新。

Is there any way to modify this code or maybe you have some other code suggestions?

有什么方法可以修改此代码,或者您有其他一些代码建议吗?

回答by JakeGould

Your question is:

你的问题是:

How to test MySQL connection in PHP and Laravel?

如何在 PHP 和 Laravel 中测试 MySQL 连接?

But then you are setting up a standard PHP MySQLi connection like this:

但是,您正在设置一个标准的 PHP MySQLi 连接,如下所示:

$connection = mysqli_connect($database_host,$database_user,$database_password,$database_name);

Why would you do that? The whole purpose of using a framework is to work within the framework. And something that encompasses these two basic systems concepts:

为什么要这么做?使用框架的全部目的是在框架内工作。以及包含这两个基本系统概念的东西:

  • Read a configuration file.
  • Establish a database connection.
  • 读取配置文件。
  • 建立数据库连接。

Doing those things is something that pretty much every capable—and widely adopted—programming framework should be able to handle within it's own structure & using it's own methods.

做这些事情几乎是每个有能力且被广泛采用的编程框架都应该能够在它自己的结构内处理并使用它自己的方法。

So that said, looking at the Laravel documentation on “Basic Database Usage”shows the following. This is placed in your DB configuration file located in app/config/database.php.:

也就是说,查看有关“基本数据库使用”的 Laravel 文档显示以下内容。这放置在位于以下位置的数据库配置文件中app/config/database.php.

'mysql' => array(
    'read' => array(
        'host' => '192.168.1.1',
    ),
    'write' => array(
        'host' => '196.168.1.2'
    ),
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

The example has two distinct DB connections: One for readand the other for write, but that is not how most DB connections for simple projects work. So you can set this instead also using your settings:

该示例有两个不同的 DB 连接:一个 forread和另一个 for write,但这不是大多数用于简单项目的 DB 连接的工作方式。因此,您也可以使用您的设置进行设置:

'mysql' => array(
    'host'      => Config::get('config.database_host'),
    'driver'    => 'mysql',
    'database'  => Config::get('config.database_name'),
    'username'  => Config::get('config.database_user'),
    'password'  => Config::get('config.database_password'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Then to test that connection, you would just do this:

然后要测试该连接,您只需执行以下操作:

if(DB::connection()->getDatabaseName())
{
   echo "Yes! successfully connected to the DB: " . DB::connection()->getDatabaseName();
}

But that said you are also saying:

但那是说你也在说:

I'm making a PHP application installer…

Why reinvent the wheel when PHP build systems such as Phingexist?

当 PHP 构建系统Phing存在时,为什么要重新发明轮子?

回答by The Alpha

You can simply check whether the connection is made or not using this:

您可以使用以下命令简单地检查是否建立了连接:

if(DB::connection()) {
    // connection is made
}

Because you don't need to make connection manually. If the user provided right credentials in the app/config/database.phpthen the user will be able to query in the database but if you need to check the connection then given code above is able to check because if the connection is not made then an error will be thrown and on a valid connection the Illuminate\Database\MySqlConnectionobject will be returned. So, in this case it's also possible to use:

因为您不需要手动进行连接。如果用户提供了正确的凭据,app/config/database.php那么用户将能够在数据库中进行查询,但是如果您需要检查连接,那么上面给出的代码能够检查,因为如果没有建立连接,则会引发错误并继续Illuminate\Database\MySqlConnection将返回对象的有效连接。因此,在这种情况下,也可以使用:

if(DB::connection() instanceof Illuminate\Database\MySqlConnection) {
    // connection is made
}

So, according to your example of TestDatabaseConnectionmethod you can do something like this:

因此,根据您的TestDatabaseConnection方法示例,您可以执行以下操作:

public function TestDatabaseConnection(){
    // Returns Illuminate\Database\MySqlConnection on successful
    // connection; otherwise an exception would be thrown if failed
    return DB::connection();
}

回答by Tzook Bar Noy

If you really want to catch the error of laravel db connection failure, you can define this:

如果你真的想捕捉laravel db连接失败的错误,你可以这样定义:

 App::error(function(PDOException $exception, $code)
 {
     die('do what you want here');
 });

I defined it inside:

我在里面定义了它:

/app/start/global.php

you can define it where ever you like.

你可以在任何你喜欢的地方定义它。