简体   繁体   English

当我尝试使用 MySQLi 连接到数据库时 PHP 退出

[英]PHP Exits When I Try to Connect to a Database Using MySQLi

I have been developing a website recently, and I came across an error.我最近在开发一个网站,遇到了一个错误。 When I tried to do print_r(error_get_last());当我尝试做print_r(error_get_last()); It output some text about mysql not being supported anymore, and to use MySQLi.它输出一些关于不再支持 mysql 的文本,并使用 MySQLi。 I was all for it.我全力以赴。 When I edited my database class to support MySQLi, it exits every time it tries to connect.当我编辑我的数据库类以支持 MySQLi 时,它每次尝试连接时都会退出。 I have put echo 'hi<br />';我已经把echo 'hi<br />'; before and after the mysqli function, and a or trigger_error("Error: " . print_r(error_get_last()));mysqli函数之前和之后,还有一个or trigger_error("Error: " . print_r(error_get_last())); at the end of it, but all it outputs is hi , and nothing else.在它的最后,但它输出的所有内容都是hi ,没有别的。 My database is created in phpMyAdmin, and has all the correct permissions, but it just cannot connect.我的数据库是在 phpMyAdmin 中创建的,并且具有所有正确的权限,但它就是无法连接。 This is my connection code:这是我的连接代码:

echo 'hi<br />';
$this->db = mysqli($host, $dbuser, $dbpass, $dbname) or trigger_error("Error: " . print_r(error_get_last()));
echo 'hi<br />';
$this->connect_start = microtime(true);
if ($this->db->connect_errno > 0) die ($this->debug(true));

It is in the constructor of a class that looks like this:它在一个类的构造函数中,如下所示:

function db($host, $dbname, $dbpass, $dbuser)

and it is called like this:它是这样调用的:

$db = new db($host, $dbname, $dbpass, $dbuser);

Change this:改变这个:

$this->db = mysqli() 

to

$this->db = new mysqli()

mysqli is not a function, it's a class. mysqli 不是一个函数,它是一个类。 If you had error reporting on you'd get a message like this:如果您有错误报告,您会收到如下消息:

PHP Fatal error: Call to undefined function mysqli() PHP 致命错误:调用未定义的函数 mysqli()

That's the reason why the rest of your code isn't executed, the execution stops right there.这就是为什么没有执行其余代码的原因,执行就在那里停止。

Also note that new mysqli() will never return false , so your or ... part becomes useless.另请注意, new mysqli()永远不会返回false ,因此您的or ...部分变得无用。 If you want to check for connection errors you have to check $this->db->connect_error after the connection attempt.如果你想检查连接错误,你必须在连接尝试后检查$this->db->connect_error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM