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!";
}

图片转代码服务由CSDN问答提供 功能建议

设置与数据库的连接的最佳做法是什么。 使用普通数组还是关联数组? 当我使用关联数组时我有这个错误警告:mysqli :: __ construct():( HY000 / 1044):用户''@ localhost'拒绝访问C:\ xampp \ htdocs \ cms \中的数据库'cms' 在第21行包含\ db.php,但它表示已连接。 我们已连接!

 &lt;?php 
 //存储数据库主机,用户,  pass,name into array 
 
 / * $ db ['db_host'] =“localhost”; 
 $ db ['db_user'] =“root”; 
 $ db ['db_pass'] =“”;  
 $ db ['db_name'] =“cms”; * / 
 
 / * $ db = array(“db_host”=&gt;“localhost”,
“db_user”=&gt;“user”,\  n“db_pass”=&gt;“”,
“db_name”=&gt;“cms”); * / 
 
 //我们循环遍历每个数组
foreach($ db as $ key =&gt; $ 值){
 
define(strtoupper($ key),$ value); 
 
} 
 
 $ connection = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME); 
 
if(isset($ 连接)){
 echo“我们已连接!”; 
}其他{
 echo“连接失败!”; 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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;
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题