douyuan9512 2017-09-28 06:51
浏览 72
已采纳

php mysqli使用数组连接

what is better practice for setting your connection to the database. using normal arrays or associative array? and when i use associative array i have this error Warning: mysqli::__construct(): (HY000/1044): Access denied for user ''@'localhost' to database 'cms' in C:\xampp\htdocs\cms\includes\db.php on line 21, but it says that im connected. We are connected!

<?php
//stores the database host,user,pass,name into array

/*$db['db_host'] = "localhost";
$db['db_user'] = "root";
$db['db_pass'] = "";
$db['db_name'] = "cms";*/

/*$db = array("db_host"=>"localhost",
        "db_user"=>"user",
        "db_pass"=>"",
        "db_name"=>"cms");*/

//we loop through each of the array
foreach ($db as $key => $value){

define(strtoupper($key), $value);

}

$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if(isset($connection)){
    echo "We are connected!";
}else{
    echo "Connection failure!";
}
  • 写回答

1条回答 默认 最新

  • doulun1915 2017-09-28 07:13
    关注

    In condition your are using wrong way isset is only check whether variable is set or not. $connection is set(if its connected or not. If connection has issue it will contain error) so change your condition as:

    if(!($connection->connect_error)){ //not containing error
        echo "We are connected!";
    }else{ //has error
        echo "Connection failure!".$connection->connect_error;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?