mysqli connect error php
mysqli::$error
Описание
Возвращает сообщение об ошибке последнего вызова функции MySQLi, который может успешно выполниться или провалиться.
Список параметров
Возвращаемые значения
Строка с описанием ошибки. Пустая строка, если ошибки нет.
Примеры
Результат выполнения данных примеров:
Смотрите также
User Contributed Notes 7 notes
The mysqli_sql_exception class is not available to PHP 5.05
?>
This would output something like:
Unexpected PHP error [mysqli::query() [function.query]: (42S22/1054): Unknown column ‘XXname’ in ‘field list’] severity [E_WARNING] in [G:\database.php] line [249]
Very frustrating as I wanted to also catch the sql error and print out the stack trace.
( MYSQLI_REPORT_OFF ); //Turn off irritating default messages
//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column ‘XXname’ in ‘field list’
Query:
SELECT XXname FROM customer_table
This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.
If you have the following situation
you don’t get an error-message, if the ROLLBACK-Query didn’t failed, too. In order to get the right error-message you have to write:
I had to set mysqli_report(MYSQLI_REPORT_ALL) at the begin of my script to be able to catch mysqli errors within the catch block of my php code.
Initially, I used the below code to throw and subsequent catch mysqli exceptions
This works fine and I ‘m able to trap all mysqli errors
Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.
So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().
As far as I can tell the two escape functions don’t escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).
PHP mysqli connect_error() Function
Return the error description from the last connection error, if any:
Look at example of procedural style at the bottom.
Definition and Usage
The connect_error / mysqli_connect_error() function returns the error description from the last connection error, if any.
Syntax
Object oriented style:
Procedural style:
Technical Details
Return Value: | Returns a string that describes the error. NULL if no error occurred |
---|---|
PHP Version: | 5+ |
Return the error description from the last connection error, if any:
We just launched
W3Schools videos
COLOR PICKER
LIKE US
Get certified
by completing
a course today!
CODE GAME
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Web Courses
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Should we ever check for mysqli_connect() errors manually?
The PHP manual for mysqli_connect() suggests checking for the return value and displaying the error messages on the screen.
Similarly for OOP-style constructor this is suggested:
Some users on Stack Overflow even used code with mysqli_error($conn) such as this:
However, in the past few weeks I have been asking myself a question, why would I need to do that? The output of the first example is:
Warning: mysqli_connect(): (HY000/1045): Access denied for user ‘my_user’@’localhost’ (using password: YES) in C:\xampp\. \mysqli.php on line 4
Error: Unable to connect to MySQL. Debugging errno: 1045 Debugging error: Access denied for user ‘my_user’@’localhost’ (using password: YES)
As you can see the error message is displayed twice! The manual «debugging» actually provides less information.
Should we ever manually check for connection errors? Would we ever get more information this way than from the automatic warning? Is this the recommended practice?
1 Answer 1
Never display connection errors manually!
MySQLi will generate a warning if it is unable to open the connection to MySQL. This warning tells you all you need to know including the error code, error message, and the place in the code where it happened. Checking for the error manually will not give you any more information.
If there is no warning in the error logs, it could mean that your PHP has error reporting silenced (either completely or just warnings). Check your PHP configuration.
In the production environment these settings should be maintained:
In the development environment these settings should be maintained:
As you can see in the error message your database username and password has been revealed to the end-user. These are sensitive information which you do not want to show anyone. In fact, a normal user would not understand this cryptic message. This is why display_errors must always be switched off in the production environment. Logging the errors on the server is safe.
Warnings vs. Exceptions
Do not catch the exceptions unless you really know what to do with them! One possible use case is described in How to connect properly using mysqli
Can mysqli_error() show any connection-related problems?
Warning: mysqli_error(): Couldn’t fetch mysqli in C:\.
PHP Warning: mysqli_connect(): (HY000/2002): Connection refused
I am using PHP 5.5 and MAMP (downloaded from here):
I have a basic script like this:
and when I run this script I get this error:
Is there some configuration issue that I need to set up within MAMP or PHP?
7 Answers 7
Sometimes you need to include mysql db port id in the server like so.
For me to make it work again I just deleted the files
Mac 10.13.3
MAMP:Version 4.3 (853)
You have to change the mamp Mysql Database port into 8889.
In my case I was using XAMPP, and there was a log that told me the error. To find it, go to the XAMPP control panel, and click «Configure» for MySQL, then click on «Open Log.»
The most current data of the log is at the bottom, and the log is organized by date, time, some number, and text in brackets that may say «Note» or «Error.» One that says «Error» is likely causing the issue.
For me, my error was a tablespace that was causing an issue, so I deleted the database files at the given location.
Note: The tablespace files for your installation of XAMPP may be at a different location, but they were in /opt/lampp/var/mysql for me. I think that’s typical of XAMPP on Debian-based distributions. Also, my instructions on what to click in the control panel to see the log may be a bit different for you because I’m running XAMPP on an Ubuntu-based distribution of Linux (Feren OS).
Fatal error: Call to undefined function mysqli_connect()
For 2 days now I’m trying to solve this, but unfortunately no result. Let me tell you my story about the problem. I’ve bulid an application on a site, and the application deals with the reviews. But, I’m trying to put it on another site, and I copyed the php files, the sql file from the old site, and moved them to the new site (they are on different FTP servers). When I’m trying to go to the pages from the application, I receive this FATAL ERROR:
Fatal error: Call to undefined function mysqli_connect()
The code that I wrote to connect to the database is this (with hidden credentials):
Why do I get the error? It works on the old server, and the code I think it’s not the problem, because it works on localhost, and on the new server it doesn’t. Can anyone help me?
14 Answers 14
If you host the server yourself, in the php.ini file remove the semicolon in front of the extension extension=php_mysqli.dll
sudo apt install php-mysqli
It works perfectly and it is version independent
On Ubuntu I had to install php5 mysql extension:
Late to the conversation.
If you have the module installed and set your PHP.INI file properly, check your apache error log for something like the following:
In this case, your extension directory is not what you think it is. You may neeed to set it explicitly, like so:
Mine was a bit different for php7 on centos7.
If you host the server yourself, and that server happens to be Apache, you can also get this error even if you have uncommented extension=php_mysqli.dll in php.ini.
You also need to tell Apache where to find php.ini by using the PHPIniDir directive in Apache’s httpd.conf
On Raspberry Pi I had to install php5 mysql extension.
After installing the client, the webserver should be restarted. In case you’re using apache, the following should work:
if you use ubuntu 16.04 (maybe and above),you have this module already but not enabled by default. Just do this:
There is no error in the, but the mysqli PHP extension is not installed on your machine. Please contact your service provider to fix this issue.
Mysqli isn’t installed on the new server. Run phpinfo() to confirm.
So this may not be the issue for you, but I was struggling with this error. I discovered what was causing my problem, though I can’t really explain as to why.
For me, mysqli_connect was working fine where the connection was made on pages in any various sub-directory. For some reason though, the same code referenced on pages in the root directory was returning this error. The strange thing is that it was working fine on my localhost environment in MAMP in the root directory, however on my shared host it was not.
After struggling to figure out what was giving me «Error 500» white screen from this «PHP Fatal Error,» I went through the code and stumbled upon this code in the error handling that was suggested by the PHP Manual (https://www.php.net/manual/en/mysqli.error.php).
I randomly decided to remove it and, voila, connection to the database working in root directories. Maybe someone smarter than me can explain this, for anyone struggling with a similar issue.