drxkx6149 2017-03-16 08:22
浏览 184
已采纳

new mysqli - 为什么会显示错误消息

I want to check if accessing mysql is possible or not.

I don't wont to have an error message, only true/false if the connection is ready or not.

I tried to do it with this :

$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
  if ($appDB->connect_error) 
  { $res['code']=FALSE; } 
  else 
  { 
    $appDB -> close();
    $res['code']=TRUE; 
  }

But always a error message will come up - how can i prevent this message from showing ?

"<b>Fatal error</b>:  Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user ''
@'localhost' (using password: NO)' in /is/htdocs/...mypath
.php:33
Stack trace:
#0 /is/htdocs...mypath.myfile.php(33): mysqli-&gt;mysqli('', ''
, '', '')
#1 {main}
  thrown in <b>/is/htdocs/wp1076647_373QG1K1B0/butobo/module/4/code/cms_checkcon.php</b> on line <b>33
</b><br />"
  • 写回答

2条回答 默认 最新

  • doutuan6158 2017-03-16 08:27
    关注

    You need to "catch" this fatal exception via a try/catch statement. This allows you to handle the fatal error and then instead of your script crashing due to it, you can output an error message and exit instead :D

    PHP Exceptions: http://php.net/manual/en/language.exceptions.php

    I hope this helps.

    try
    {
        $appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
          if ($appDB->connect_error) 
          { $res['code']=FALSE; } 
          else 
          { 
            $appDB -> close();
            $res['code']=TRUE; 
          }
    }
    catch (Exception $e)
    {
        echo 'Caught exception: ',  $e->getMessage(), "
    ";
        exit;
    }
    

    This will change the ERROR to a WARNING, which will not break your script. From there, if you want to hide everything EXCEPT fatal errors, you can use this line of PHP:

    error_reporting(E_ERROR);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀