Скрипт:
<?php
$db_host = ;
$db_user = ;
$db_password = ;
$db_name = ;
$link = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if (!$link) {
die('<p style="color:red">'.mysqli_connect_errno().' - '.mysqli_connect_error().'</p>');
}
echo "<p>Вы подключились к MySQL!</p>";
?>
выводит код:
2002 — php_network_getaddresses: getaddrinfo failed: Name or service not known
скрипт находится на хостинге: hostiman.ru
В чём суть ошибки?
I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Before I was receiving an error message of:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
Any help regarding this would be appreciated.
asked Apr 1, 2015 at 15:57
4
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
answered Apr 1, 2015 at 21:15
JonckJonck
1,5591 gold badge10 silver badges15 bronze badges
4
I spent quite a few hours in a docker
environment where all my containers are docker
containers and I was using Phinx
for migrations. Just to share different responses with different configurations.
Working solutions
"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked
Non-working solutions
"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", // SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", // SQLSTATE[HY000] [2002] No such file or directory
I was running Phinx
in following way.
docker compose --env-file .env run --rm phinx status -e development
answered Jun 21, 2022 at 11:01
GoharSahiGoharSahi
4661 gold badge8 silver badges21 bronze badges
2
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the «initctl» utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with «initctl» utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get
the process id (pid), simulate a failure by killing the «mysql»
process and verify its status as running with new process id after
sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
answered Oct 16, 2018 at 9:52
vinodvinod
2,8201 gold badge18 silver badges23 bronze badges
3
Using MAMP I changed the host=localhost
to host=127.0.0.1
. But a new issue came «connection refused»
Solved this by putting 'port' => '8889'
, in 'Datasources' => [
answered Mar 31, 2019 at 9:55
1. server cert verify flag
I was required to use SSL to connect, and needed to set PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT
to false in the new PDO
options array, besides the entry PDO::MYSQL_ATTR_SSL_CA
for the CA file.
Without it, the mysql log on the server helpfully mentions
2021-07-27 17:02:51 597605 [Warning] Aborted connection 597605 to db: 'unconnected' user: 'unauthenticated' host: '192.168.10.123' (This connection closed normally without authentication)
where I was definitely passing the right db and username and such in the DSN. An empty options array will show the db and user in the error log, at least. I am sure there is a valid, technical reason for these things.
I am adding this information so I can more easily find it, the next time I end up on this page..
2. host in connection string
In the context of SSL, I’ve also seen the error when using the IP address instead of the hostname to connect, if the hostname was used as CN (Common Name) in the certificate.
answered Jul 27, 2021 at 15:20
MSpreijMSpreij
1,14313 silver badges20 bronze badges
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
answered Jul 11, 2020 at 15:58
DeyDey
8439 silver badges21 bronze badges
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
-
In terminal run
vim ~/.bash_profile
to open~/.bash_profile
-
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH=»/Applications/mampstack-7.1.21-0/php/bin/:$PATH»
-
Hit
ESC
, Type:wq
, and hitEnter
- In Terminal run
source ~/.bash_profile
- In Terminal type
which php
, output should be the path to MAMP PHP install.
answered Jan 29, 2020 at 15:11
MahdiyehMahdiyeh
73510 silver badges12 bronze badges
I had the same issue on a docker container from php:8.0-fpm-alpine
image. I just added the following line in the Dockerfile and it fixed the issue:
RUN apk add mysql-client
answered Oct 12, 2021 at 19:58
Omid EbrahimiOmid Ebrahimi
1,1502 gold badges20 silver badges38 bronze badges
I had a similar problem once, turned out the User in the database was created with something like:
CREATE USER 'webpage'@'localhost' IDENTIFIED BY 'password';
worked fine when the connection details php script had localhost, but not when the IP address was there. A quick swap (ip address when creating user and localhost in connection details) revealed those two things have to match.
answered Aug 12, 2022 at 19:49
1
For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.
answered Jan 26, 2021 at 17:05
1
I had a similar issue when trying to migrate a Drupal website from one local host to another. From Mac running XAMMP to Windows running WAMP.
This was the error message I kept getting when trying to access the pages of the website.
PDOException: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
in drupal_get_installed_schema_version() (line 155 of C:wampwwwchiaincludesinstall.inc).
In settings.php, I’ve changed everything correctly, database name, user and password.
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'mydatabasename',
'username' => 'mydbusername',
'password' => 'mydbpass',
'host' => 'localhost',
'port' => '8889',
'driver' => 'mysql',
'prefix' => '',
),
),
);
After a couple of hours of mindless google searching I’ve changed the port to a empty value:
'port' => '',
And after that the site loaded properly.
После перезапуска MySQL сервера у меня случился сбой, который выдавал ошибку ERROR 2002 (HY000). С такой проблемой я раньше не сталкивался, поэтому начал активно искать решение…
Непосредственно сам код ошибки выглядел так:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Для начала я попытался убить соответствующий PID, как рекомендуют на большинстве форумов, однако это ничего не дало. Поэтому я продолжил искать решение проблему и нашел команду, которая все исправила.
Вообще, эта проблема не новая и интернет переполнен различными вариантами решения. Свое решение я нашел в этом посте на StackOverflow.
sudo chown -R _mysql:mysql /usr/local/var/mysql && sudo brew services restart mysql
После этого, проблема решилась и сервер успешно запустился, поэтому можно работать с данными дальше 😎
Databases play a critical role in the proper working of any web applications. They store, organize and manage a large amount of user data.
Any problem with database connectivity can cause website errors. And the error show up as “sqlstate hy000 error 2002.”
At Bobcares, we specialize in fixing database errors for our customers as part of our Server Management Services.
Today, we’ll see various reasons for sqlstate hy000 error 2002 and how our Database Engineers fix it.
Examining sqlstate 2002 error
Before we dive into the solution, let’s first check the sqlstate 2002 error in detail.
In general, when we configure any PHP application, we specify the details of the database in the configuration file. The same is applicable in case of popular content management systems like WordPress, Joomla, Magento, etc. And, when we update or change any setting in the website, it gets saved on the database. For this to work, there should not be any problem with database connection with MySQL host server.
The database connection can fail due to reasons like wrong database details in the configuration file, port restrictions on the server, missing files, lack of resources on the server and so on.
In simple terms, MySQL error 2002 denotes a problem of connection between the website code and the database.
There are many variants of the sqlstate hy000 2002 error. The details are readily available in the second part of the error message.
From our experience in managing servers, our Dedicated Engineers see variants of sqlstate hy000 error 2002 as
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
SQLSTATE[HY000] [2002] Resource temporarily unavailable
exit status 3
Again, a similar error on a Magento website appear as :
What causes sqlstate hy000 error 2002?
Now, let’s have a look on the possible causes for sqlstate hy000 error 2002.
1.MySQL server not running
In many of the cases where websites report sqlstate 2002 error, the underlying reason would be stopped MySQL server. And, this can happen due to broken MySQL libraries, resource crunch on the server, etc. When MySQL is not running on the server, the website will not be able to connect to the database and its reports “Connection refused
error.
2. Incorrect database settings
Similarly, a major reason for sqlstate hy000 2002 error is the incorrect database settings in the configuration file. For the proper working of the program, the file should contain correct database server name, database user details and password.
If the MySQL service is listening on 127.0.0.1, the same settings should be given in the database connection string. Moreover, the MySQL server should accept connections on this IP address too.
3. Insufficient server resources
Last and not the least, insufficient server resources also can be a reason for MySQL errors. When the server has too many MySQL queries, it requires too much server memory. Additionally, when websites use resource intensive queries, it add to the server load and lack of memory on the server. It ends up in errors like “SQLSTATE[HY000] [2002] Resource temporarily unavailable.”
How we fix sqlstate hy000 error 2002
Let’s take a look on how our Dedicated Engineers helped one of our customers to fix the sqlstate hy000 error 2002.
The customer was using a PHP tracking script on his website. There was a high volume of MySQL activity (about 4 inserts a second), from this tracking script, and this was causing the MySQL Connection time out error. And, on the website it resulted in error:
Exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Connection timed out
It was a sign of PHP script timing out while connecting to MySQL host.
1. Ensure MySQL running status
Here, we first checked the status of MySQL server. It was running fine on the server as per the snippet below.
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2019-03-09 15:25:43 xx; 2 weeks 5 days ago
Therefore, we isolated the problem with MySQL server status.
2. Correcting Configuration file
As the second step, we checked and confirmed that the script was using correct Database details including Hostname, User and Password. Moreover, the website was showing data from the database too. Thus, the connection was happening. The error was happening only at certain intervals.
Additionally, we checked that MySQL database user was able to connect from the command line.
3. Fixing server resources
Since we already ruled out configuration errors, the next thing to check was the server resources. Here, our Dedicated Engineers checked the memory usage on the server. We found that MySQL memory usage was high in the server (around 89% of available memory).
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
30571 mysql 20 0 58.947g 0.055t 9832 S 135.1 89.2 16872:22 /usr/sbin/mysqld
The memory usage statistics on the server looked as below.
We could see that there was a scope for MySQL tweaks in the server. Therefore, we analyzed the MySQL server performance by watching the MySQL queries and its impact on the server. Then our expert Database Engineers tweaked certain MySQL parameters such as join_buffer_size, table_open_cache and innodb_buffer_pool_instances.
After the tweaking, we restarted MySQL services at off-peak hours to minimize the impact on live websites. The performance on the MySQL server improved drastically and it fixed sqlstate hy000 error 2002 as well.
[Looking for tweaking MySQL server for improved performance? Our MySQL experts are available 24×7.]
Conclusion
In short, sqlstate hy000 error 2002 can happen due to stopped MySQL server, insufficient server resources, etc. Today we saw how our Dedicated Engineers troubleshooted and fixed MySQL errors for one of our customers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;