Home  >  Article  >  Backend Development  >  连接出错后为什么还会执行else后的语句?解决办法

连接出错后为什么还会执行else后的语句?解决办法

WBOY
WBOYOriginal
2016-06-13 13:32:55792browse

连接出错后为什么还会执行else后的语句?

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><?php $mysqli=new mysqli('localhost','root','root1','mydb');

    if ($mysqli->connect_error){
        die("连接失败".$mysqli->connect_error);
    }else{
        echo "连接成功";
    };
?>

上面代码,我故意把root写成root1,如果不改,页面显示连接成功,可是连接出错页面会显示如下
Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user 'root'@'localhost' (using password: YES) in C:\wamp\www\Project1\f.php on line 2

Warning: main() [function.main]: Couldn't fetch mysqli in C:\wamp\www\Project1\f.php on line 4
连接成功
为什么连接出错了,没有显示die里的 连接失败 信息?
如果连接失败,为什么还会显示else里的连接成功?

------解决方案--------------------
很简单
当连接失败后, $mysqli 就是无效的
if ($mysqli->connect_error)
就会因为 $mysqli 不是对象,而不能进入 true 分支

于是只会执行 echo "连接成功";
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn