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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 准备学习小程序搭建,谁能手把手的教我啊?
  • ¥15 第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没法联网
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)