doubipiao1611 2018-05-20 11:44
浏览 19
已采纳

连接数据库不会打印出错误

I have a function to connect to a DB. I also check if that went through, however, when I fail it intentionally, it doesn't print out the errors in the if(!$db) brackets.

function connectToDb(){
    //Connect to a database
    $db = new mysqli("localhost", "root", "", "vm_ski");
    if(!$db){
        echo "error: ConnectToDB failed";
        printError("Could not connect to db: ".$db->error);
    }
    else{
        echo "OK";
        return $db;
    }
}

It prints out the warning from PHP: Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: NO) which I get. But why does it still print out "OK" in the else, shouldn't it call printError?

  • 写回答

3条回答 默认 最新

  • duanba3707 2018-05-20 11:57
    关注

    here is php document example of mysqli to deal with error

    http://php.net/manual/en/mysqli.quickstart.connections.php

    <?php
    $mysqli = new mysqli("localhost", "user", "password", "database");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    echo $mysqli->host_info . "
    ";
    
    $mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    
    echo $mysqli->host_info . "
    ";
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?