Home » Php » How verify mysql database connection from another file php

How verify mysql database connection from another file php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’ve created a form where the user can add his database name, username, password, host. then that form creates a config file and adds the user database details. the form is in root and the config file is in root/includes. I want to know how can I verify database connection from form file. if the connection is successful he can proceed to the next step and if it’s not I want to show the error.

Form

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['db-details']) {

    $dbName = $_POST['dbName'];
    $dbUsername = $_POST['dbUsername'];
    $dbPassword = $_POST['dbPassword'];
    $dbHost = $_POST['dbHost'];

    $phConfigFile = 'includes/ph_config.php';

    file_put_contents($phConfigFile, $phConfigData);

}

Config

<?php 

    define("DB_HOST", "[dbHost]");

    define("DB_USER", "[dbUsername]");

    define("DB_PASS", "[dbPassword]");

    define("DB_NAME", "[dbName]");

    $connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
How to&Answers:

You really want to check the connection before you create the config file, so once created you know it will work

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['db-details']) {

    $dbName     = $_POST['dbName'];
    $dbUsername = $_POST['dbUsername'];
    $dbPassword = $_POST['dbPassword'];
    $dbHost     = $_POST['dbHost'];

    // use error supression so you get to process the error rather 
    // than PHP throwing an error
    $connection = @mysqli_connect($_POST['dbHost'], 
                                $_POST['dbUsername'], 
                                $_POST['dbPassword'], 
                                $_POST['dbName']);

    if ( ! $connection ) {
        // do whatever you need to when the information passed does not work
        exit;
    }

    // must be valid as we connected

    $str = '<?php' . PHP_EOL;
    $str .= 'define("DB_HOST", "' . $_POST['dbHost'] . '");'        . PHP_EOL;
    $str .= 'define("DB_USER", "' . $_POST['dbUsername'] . '");'    . PHP_EOL;
    $str .= 'define("DB_PASS", "' . $_POST['dbPassword'] . '");'    . PHP_EOL;
    $str .= 'define("DB_NAME", "' . $_POST['dbName'] . '");'        . PHP_EOL; 

    $str .= '$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);' . PHP_EOL;

    // create the config file in all confidence that the values will work
    file_put_contents($phConfigFile, $str);    
}

Answer:

This is the same as RiggsFolly answer, but improved.

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['db-details'])) {
    try {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $connection = new mysqli(
            $_POST['dbHost'],
            $_POST['dbUsername'],
            $_POST['dbPassword'],
            $_POST['dbName']
        );

        $DBconfig = [
            'dbHost' => $_POST['dbHost'],
            'dbUsername' => $_POST['dbUsername'],
            'dbPassword' => $_POST['dbPassword'],
            'dbName' => $_POST['dbName']
        ];

        // generate the config file
        $contents = '<?php' . PHP_EOL;
        $contents .= '$DBconfig = ' . var_export($DBconfig, true) . ';' . PHP_EOL;
        $contents .= 'mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);' . PHP_EOL;
        $contents .= '$connection = new mysqli(
            $DBconfig["dbHost"],
            $DBconfig["dbUsername"],
            $DBconfig["dbPassword"],
            $DBconfig["dbName"]
        );';
        echo $contents;
    } catch (\Exception $e) {
        // echo error message here and show the same form. 
    }
}

Basically, you should avoid the error suppression operator at all cost. Thankfully PHP has exceptions, which can be caught and handled.

If there’s no exception you can put the connection details in an array and then export that array into a string. Generate the connection file and save it.

Another thing I would improve is to encapsulate this in a function to prevent the config details spilling out.

// generate the config file
$contents = '<?php' . PHP_EOL;
$contents .= 'function db_connect():\mysqli { '. PHP_EOL;
$contents .= '$DBconfig = ' . var_export($DBconfig, true) . ';' . PHP_EOL;
$contents .= 'mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);' . PHP_EOL;
$contents .= 'return new mysqli(
    $DBconfig["dbHost"],
    $DBconfig["dbUsername"],
    $DBconfig["dbPassword"],
    $DBconfig["dbName"]
);';
$contents .= PHP_EOL;
$contents .= '}'.PHP_EOL;
$contents .= '$connection = db_connect();'.PHP_EOL;
echo $contents;

Answer:

So if i get you right, you want to know if the data the user enters is actually valid to connect to a server. Not validating it.

You can include the file you just wrote and test it.

Just make sure you’re using the same variable name after the include.

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['db-details']) {

 $dbName = $_POST['dbName'];
 $dbUsername = $_POST['dbUsername'];
 $dbPassword = $_POST['dbPassword'];
 $dbHost = $_POST['dbHost'];

 $phConfigFile = 'includes/ph_config.php';

 file_put_contents($phConfigFile, $phConfigData);

 include($phConfigFile);

 if ($connection->connect_errno) {
  //data for the connection isn't valid
  echo "Failed to connect to MySQL: " . $connection->connect_error;
  exit();
 }

}