mysqli object variable from request key

2019-09-02 10:04发布

问题:

Im not sure if this is possible. here is what i have

if ($_REQUEST[db]=="abcd"){   
    $result =$abcdsqli->query("SELECT * FROM ...");
}elseif ($_REQUEST[db]=="efgh"){   
    $result =$efghsqli-> ...
}

here is what i want

$result =$.$_REQUEST[db].sqli->query("SELECT * FROM ...");

回答1:

Why do you need so many mysqli objects?

And using $_RESQUEST in your code so openly like that can lead to many many hacks on your site.

Just use one (one[1]) mysqli object.


I advise to NOT USE THIS but this is what you want:

$sql = "{$_REQUEST['db']}sqli";
$$sql->query("SELECT * FROM ...");

So if $_REQUEST['db'] == 'abc' It would be doing:

$abcsqli->query("SELECT * FROM ...");


回答2:

Your question is perfect for the factory pattern using a singleton. This code is skeletal, meaning there is 0 validation, etc., but should give you an idea.

class Database
{
    private static $dbos = array();

    public static function getDbo($dboKey)
    {
        if (!isset(self::$dbos[$dboKey])) {

            switch ($dboKey) {
                case 'abcd':
                    $dbo = new mysqli('localhost', 'my_user', 'my_password', 'my_db_1'); 
                    break;

                case 'efgh':
                    $dbo = new new mysqli('localhost', 'my_user', 'my_password', 'my_db_2');
                    break;
            }

            self::$dbos[$dboKey] = $dbo;
        }

        return self::$dbos[$dboKey];
    }        
}

$result = Database::getDbo($_REQUEST[db])->query("SELECT * FROM ...");