establishing connection from include file

2019-08-12 17:08发布

问题:

The connection file has the following code

<?php
return array(
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'dbname',
            'username'  => 'root',
            'password'  => 'dbpass',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

    ),

);

And i am including the above connection file in another page. I can't edit the config.php due to some reasons.

But How can i do the regular mysqli connection with the above array ?

i.e.,

<?php
include('../config/config.php');
//$mysqli = new mysqli("localhost", "root", "", "wolly");  // need to do the connection
$query = "SELECT * FROM action";
$result = $mysqli->query($query)

As in the above the i need the variable $mysqli as the to make the result. But my question is How can i get the values inside the array from config.php ?

Note : I can't make any changes or declare the $mysqli in the config.php

回答1:

This should work for you.

$array = include('../config/config.php');

$mysql_conn = $array['connections']['mysql'];

$mysqli = new mysqli($mysql_conn['host'], $mysql_conn['username'],
                     $mysql_conn['password'], $mysql_conn['database']);

$query = 'SELECT * FROM action';
$result = $mysqli->query($query);