One of simplest reasons for this error is that a MySQL server is not running. So verify that first. In case it’s up, proceed to other recommendations:
Laravel 4: Change «host» in the
app/config/database.php
file from «localhost» to «127.0.0.1»Laravel 5+: Change «DB_HOST» in the
.env
file from «localhost» to «127.0.0.1»
I had the exact same problem. None of the above solutions worked for me. I solved the problem by changing the «host» in the /app/config/database.php file from «localhost» to «127.0.0.1».
Not sure why «localhost» doesn’t work by default but I found this answer in a similar question solved in a symfony2 post. https://stackoverflow.com/a/9251924
Update:
Some people have asked as to why this fix works so I have done a little bit of research into the topic. It seems as though they use different connection types as explained in this post https://stackoverflow.com/a/9715164
The issue that arose here is that «localhost» uses a UNIX socket and can not find the database in the standard directory. However «127.0.0.1» uses TCP (Transmission Control Protocol), which essentially means it runs through the «local internet» on your computer being much more reliable than the UNIX socket in this case.
answered Apr 8, 2014 at 4:07
23
The error message indicates that a MySQL connection via socket is tried (which is not supported).
In the context of Laravel (artisan), you probably want to use a different / the correct environment. Eg: php artisan migrate --env=production
(or whatever environment). See here.
answered Dec 22, 2013 at 19:08
ukautzukautz
2,1931 gold badge13 silver badges7 bronze badges
5
I got the same problem and I’m running Mac OS X 10.10 Yosemite. I have enabled the Apache Server and PHP that already comes with the OS. Then I just configured the mCrypt library to get started. After that when I was working with models and DB I got the error:
[PDOException]
SQLSTATE[HY000] [2002] No such file or directory
The reason I found is just because PHP and MySQL can’t get connected themselves.
To get this problem fixed, I follow the next steps:
-
Open a terminal and connect to the mysql with:
mysql -u root -p
-
It will ask you for the related password. Then once you get the mysql promt type the next command:
mysql> show variables like '%sock%'
-
You will get something like this:
+-----------------------------------------+-----------------+ | Variable_name | Value | +-----------------------------------------+-----------------+ | performance_schema_max_socket_classes | 10 | | performance_schema_max_socket_instances | 322 | | socket | /tmp/mysql.sock | +-----------------------------------------+-----------------+
-
Keep the value of the last row:
/tmp/mysql.sock
-
In your
laravel
project folder, look for the database.php file there is where you configure the DB connection parameters. In the mysql section add the next line at the end:'unix_socket' => '/tmp/mysql.sock'
-
You must have something like this:
'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'SchoolBoard', 'username' => 'root', 'password' => 'venturaa', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'unix_socket' => '/tmp/mysql.sock', ),
Now just save changes, and reload the page and it must work!
M—ßţřịƙïñĝ
25.1k8 gold badges57 silver badges93 bronze badges
answered Mar 6, 2015 at 18:13
alexventuraioalexventuraio
7,7162 gold badges29 silver badges34 bronze badges
15
I encountered the [PDOException] SQLSTATE[HY000] [2002] No such file or directory
error for a different reason. I had just finished building a brand new LAMP stack on Ubuntu 12.04 with Apache 2.4.7, PHP v5.5.10 and MySQL 5.6.16. I moved my sites back over and fired them up. But, I couldn’t load my Laravel 4.2.x based site because of the [PDOException]
above. So, I checked php -i | grep pdo
and noticed this line:
pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock
But, in my /etc/my.cnf the sock file is actually in /var/run/mysqld/mysqld.sock
.
So, I opened up my php.ini and set the value for pdo_mysql.default_socket
:
pdo_mysql.default_socket=/var/run/mysqld/mysqld.sock
Then, I restarted apache and checked php -i | grep pdo
:
pdo_mysql.default_socket => /var/run/mysqld/mysqld.sock => /var/run/mysqld/mysqld.sock
That fixed it for me.
answered Mar 20, 2014 at 3:51
dcarrithdcarrith
7,4402 gold badges17 silver badges9 bronze badges
2
The answer from @stuyam solved the «No such file or directory» issue for me
Short answer: Change «host» in the /app/config/database.php file from «localhost» to «127.0.0.1»
But then I had a «Connection refused» error. If anyone had the same issue, my solution for this was to update the app/config/local/database.php file so the port is 8889:
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => '8889',
'database' => 'databaseName',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
stuyam
9,4612 gold badges21 silver badges40 bronze badges
answered Jan 31, 2015 at 19:00
MarlowMarlow
4814 silver badges4 bronze badges
1
In my case i had no problem at all, just forgot to start the mysql service…
sudo service mysqld start
answered Aug 29, 2014 at 16:51
Carlos ABSCarlos ABS
6939 silver badges19 bronze badges
0
If you are using Laravel Homestead, make sure you’re calling the commands on the server.
homestead ssh
Then simply cd to the right directory and fire your command there.
answered Mar 3, 2015 at 15:04
KoenoKoeno
1,4532 gold badges14 silver badges30 bronze badges
3
It worked after I change from DB_HOST=localhost
to DB_HOST=127.0.0.1
at .env file
answered Sep 19, 2018 at 6:01
noonenoone
6,0962 gold badges40 silver badges51 bronze badges
3
This is because PDO treats «localhost» host specially:
Note: Unix only: When the host name is set to «localhost», then the
connection to the server is made thru a domain socket. If PDO_MYSQL is
compiled against libmysqlclient then the location of the socket file
is at libmysqlclient’s compiled in location. If PDO_MYSQL is compiled
against mysqlnd a default socket can be set thru the
pdo_mysql.default_socket setting.
(from http://php.net/manual/en/ref.pdo-mysql.connection.php)
Changing localhost to 127.0.0.1 will «force» the use of TCP.
Note: mysqli_connect is working fine with localhost.
answered Mar 27, 2018 at 9:04
Thomas DecauxThomas Decaux
21.5k2 gold badges113 silver badges123 bronze badges
Add mysql.sock path in database.php file like below example
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
Eample
'mysql' => [
'driver' => 'mysql',
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '8889'),
answered May 14, 2016 at 5:50
RavichandranRavichandran
1,0296 silver badges11 bronze badges
0
Mamp user enable option Allow network access to MYSQL
answered Feb 23, 2016 at 9:38
George JohnGeorge John
2,5992 gold badges21 silver badges16 bronze badges
0
Step 1
Find the path to your unix_socket, to do that just run netstat -ln | grep mysql
You should get something like this
unix 2 [ ACC ] STREAM LISTENING 17397 /var/run/mysqld/mysqld.sock
Step 2
Take that and add it in your unix_socket param
'mysql' => array(
'driver' => 'mysql',
'host' => '67.25.71.187',
'database' => 'dbname',
'username' => 'username',
'password' => '***',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'unix_socket' => '/var/run/mysqld/mysqld.sock' <-----
),
),
Hope it helps !!
answered Feb 28, 2017 at 20:16
code-8code-8
53.9k104 gold badges338 silver badges593 bronze badges
Building on the answer from @dcarrith …
Instead of editing the config files, I created an alias in the location that PHP is looking that connects to the real mysql.sock. (source)
Just run these two commands (no restart needed):
mkdir /var/mysql
ln -s /tmp/mysql.sock /var/mysql/mysql.sock
answered Oct 18, 2014 at 3:22
JustinJustin
26.1k16 gold badges109 silver badges127 bronze badges
0
I’m running on MAMP Pro and had this similar problem when trying to migrate (create db tables). Tried a few of these mentioned suggestions as well but didn’t do it for me.
So, simply (after an hour googling), I added two things to the /config/database.php.
'port' => '1234',
'unix_socket' => '/path/to/my/socket/mysqld.sock'
Works fine now!
answered Jul 18, 2015 at 10:50
anoraqanoraq
5157 silver badges9 bronze badges
Just i do one change in .env file
I have following line of code.
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=
Change host name localhost to 127.0.0.1
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=
That is work in my case because that can’t find any hostname like localhost
And after changing hostname write following command
php artisan config:clear
php artisan migrate:install
php artisan migrate
Alp Altunel
3,2841 gold badge25 silver badges27 bronze badges
answered Aug 27, 2021 at 11:56
I had this problems when I was running my application using docker containers.
The solution was put the name of the MySQL service container I was using in docker_compose.yml
on DB_HOST. In my case, it was db
:
DB_HOST=db
Hope it helps.
answered Jan 7, 2019 at 3:00
LanoLano
5931 gold badge7 silver badges13 bronze badges
2
I ran into this problem when running PHPUnit in Elixir/Gulp, and Homestead as my Vagrant enviroment.
In my case I edited the .env file from DB_HOST=localhost
to DB_HOST=192.168.10.10
where 192.168.10.10
is the IP of my Vagrant/Homestead host.
answered Sep 26, 2015 at 17:10
Check your port carefully . In my case it was 8889 and i am using 8888.
change «DB_HOST» from «localhost» to «127.0.0.1» and vice versa
answered Mar 4, 2018 at 13:44
Ahmed AwanAhmed Awan
3473 silver badges9 bronze badges
1
I had similar problems accessing my Drupal website. I fixed it by opening the command line, and restarting my MySQL server or service:
service mysqld restart
This should work. If it doesn’t, restart your local webserver:
service httpd restart
That should be enough. Hope it works for other environments, too. Note that these commands generally require superuser privileges.
answered Jul 1, 2015 at 8:26
RAWGITRAWGIT
991 silver badge3 bronze badges
I had the same problem using Docker and MySQL service name db
in docker_compose.yml file:
I added the following in the .env
file:
DB_HOST=db
you should also assure that your host is discoverable from the php app.
It was because PHP didn’t figure out which host to use to connect.
answered Mar 8, 2020 at 21:07
Oscar GallardoOscar Gallardo
2,1503 gold badges25 silver badges46 bronze badges
1
I got the same problem in ubuntu 18.04 with nginx. By following the below steps my issue has been fixd:
First open terminal and enter into mysql CLI. To check mysql socket location I write the following command.
mysql> show variables like '%sock%'
I got something like the below :
+-----------------------------------------+-----------------------------+
| Variable_name | Value |
+-----------------------------------------+-----------------------------+
| mysqlx_socket | /var/run/mysqld/mysqlx.sock |
| performance_schema_max_socket_classes | 10 |
| performance_schema_max_socket_instances | -1 |
| socket | /var/run/mysqld/mysqld.sock |
+-----------------------------------------+-----------------------------+
4 rows in set (0.00 sec)
In laravel project folder, look for the database.php file in the config folder. In the mysql section I modified unix_socket according to the above table.
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database_name',
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'unix_socket' => '/var/run/mysqld/mysqld.sock',
),
Now just save changes, and reload the page and it worked.
answered Jan 19, 2021 at 13:26
HasinurHasinur
1961 silver badge6 bronze badges
As of Laravel 5 the database username and password goes in the .env file that exists in the project directory, e.g.
DB_HOST=127.0.0.1
DB_DATABASE=db1
DB_USERNAME=user1
DB_PASSWORD=pass1
As you can see these environment variables are overriding the ‘forge’ strings here so changing them has no effect:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
More information is here https://mattstauffer.co/blog/laravel-5.0-environment-detection-and-environment-variables
answered Mar 14, 2015 at 23:38
malhalmalhal
25.5k7 gold badges113 silver badges131 bronze badges
Attempt to connect to localhost:
SQLSTATE[HY000] [2002] No such file or directory
Attempt to connect to 127.0.0.1:
SQLSTATE[HY000] [2002] Connection refused
OK, just comment / remove the following setting from my.cnf (on OS X 10.5: /opt/local/etc/mysqlxx/my.cnf
) to obtain:
[mysqld]
# skip-networking
Of course, stop and start MySQL Server.
answered Sep 28, 2015 at 13:28
solved
in my case it was a logic issue in code, the connection values are in a if statement:
if($_SERVER['HTTP_HOST'] == "localhost")
so the solution was to add a pipe and add 127.0.0.1, that solved the problem for me
if($_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "127.0.0.1")
answered Feb 13, 2022 at 15:16
If you are using Laravel Homestead,
here is settings
(include Vagrant-Virtual Machine)
.bash-profile
alias vm="ssh vagrant@127.0.0.1 -p 2222"
database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', 'secret'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Terminal
vm
vagrant@homestead:~/Code/projectFolder php artisan migrate:install
answered Jun 21, 2015 at 22:22
ErcanEErcanE
1,5313 gold badges19 silver badges27 bronze badges
0
If anyone are still looking for the answer, just check your .env file. For some reason laravel create a .env.example file, so all this answers didn’t work for me. I fixed my issue renamming .env.example to .env
answered Dec 13, 2015 at 1:20
1
This happened to me because MySQL wasn’t running. MySQL was failing to start because I had a missing /usr/local/etc/my.cnf.d/
directory.
This was being required by my /usr/local/etc/my.cnf
config file as a glob include (include /usr/local/etc/my.cnf.d/*.cnf
).
Running mkdir /usr/local/etc/my.cnf.d
, and then starting MySQL, fixed the issue.
answered Dec 14, 2016 at 18:32
james2doylejames2doyle
1,39919 silver badges21 bronze badges
In my case, I was running php artisan migrate on my mac terminal, when I needed to ssh into vagrant and run it from there. Hope that helps someone the headache.
answered Jun 6, 2018 at 17:53
BradBrad
12k44 gold badges118 silver badges186 bronze badges
In my case I had to remove the bootstrap/cache folder and try it again.
My cenario was after a server migration.
UPDATED AND WORKING
- Remove folder «cache» from bootstrap (booststrap/cache)
- Copy folder «cache» from original folder and paste it in bootstrap
- Run these commands:
3.1) php artisan config:cache
3.2) php artisan migrate
3.3) php artisan db:see
3.4) php artisan serve
That’s all.
answered Aug 28, 2019 at 21:22
1
When using a VirtualMachine make sure you ssh into that machine and navigate to your App folder and call the php artisan migrate command from there.
answered Apr 8, 2015 at 7:22
cmaccmac
3,0655 gold badges36 silver badges49 bronze badges
I have several versions of PHP available to me via the shell — typing php and pressing tab shows which ones my autocomplete knows about.
For me, PHP 5.4, 5.5 and 5.6 were all working fine, but PHP 7 wasn’t finding the mysql.sock, and was crashing with the «SQLSTATE[HY000] [2002] No such file or directory error» discussed in this question.
# Prints [ok]
echo "<?php print(new mysqli('localhost', 'root', 'root', 'mysql') ? '[ok]' : '[error]').PHP_EOL; ?>" | php-5.6.20
# Prints [error] and shows a warning
echo "<?php print(new mysqli('localhost', 'root', 'root', 'mysql') ? '[ok]' : '[error]').PHP_EOL; ?>" | php-7.0.8
To see where your mysql server has its socket, use this command:
cat /etc/mysql/my.cnf | grep socket
In my case, with Percona Mysql installed in my vagrant system the sock socket file happened to live here:
/var/run/mysqld/mysqld.sock
(notice that it is called mysqld not simply mysql)
I have several versions of php to choose from and these commands showed me which ones had issues and which ones were fine:
The answer for me was simply to include code in the vagrant provisioner script to create a symlink between /tmp/mysql.sock and /var/run/mysqld/mysqld.sock
if [ ! -L /tmp/mysql.sock ]; then
echo "Creating symbolic link for php 7 to connect to mysql.sock"
ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock
fi
With the new symlink in place, the test script given before now works perfectly for all versions of PHP and I can use localhost in my code instead of having to give the 127.0.0.1 IP address.
If you ever saw this error message in Laravel:
«SQLSTATE[HY000] [2002] No such file or directory»
most likely you have problem with configuration of database connection in your .env
file.
To fix it you have to be sure that correct DB_HOST is set in env file and the value of it should be correct. If you are in your local environment try to change from localhost to 127.0.0.1
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
...
And after you make this change do not forget to clear the config cache
But in some cases, this could also be wrong. And after you make this change you will get another error:
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `sessions` where `id` = …
This error is not really explaining the real problem, but the main problem now is that your DB_HOST IP address is definitely wrong and Laravel actually cannot make connection to this database. In order to fix it double check your DB host IP and port, and update it accordingly.
If you are using XAMPP, open it and check on which IP is working because latest version are using different local IP:
In this case you have to change DB_HOST to
do not forget to run php artisan config:clear
to apply the change.
And boom the error is gone!
If you are using some Docker or some other virtual development environment, double check the MySQL IP and port and set it correctly in .env
file
So, basically this can be fixed in these 3 steps:
- Check the correct IP address of your MySQL (or just switch localhost to 127.0.0.1)
- update DB_HOST in .env file
- run php artisan config:clear to clear the cache and apply your change
Установил nginx, php-fpm, mariadb, Laravel 5 на vps.
Laravel команды artisan работают, но команды для БД не работают:
Ввожу командуphp artisan migrate:install
Выходит ошибка
[pdoexception] sqlstate[hy000] [2002] no such file or directory
В чем проблема?
Вот мой конфиг database.php в Laravel 5:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'demo'),
'username' => env('DB_USERNAME', 'demo'),
'password' => env('DB_PASSWORD', 'dq2'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'unix_socket' => '/var/lib/mysql/mysql.sock',
'strict' => false,
],
Вот где сокет и его права:
php -i | grep pdo
/etc/php.d/20-pdo.ini,
/etc/php.d/30-pdo_mysql.ini,
/etc/php.d/30-pdo_sqlite.ini,
API Extensions => mysql,mysqli,pdo_mysql
pdo_mysql
pdo_mysql.default_socket => /var/lib/mysql/mysql.sock => /var/lib/mysql/mysql.sock
pdo_sqlite
ls -l /var/lib/mysql/mysql.sock
srwxrwxrwx. 1 mysql mysql 0 июл 31 10:01 /var/lib/mysql/mysql.sock
Вот настройки php.ini
mysql.default_socket = /var/lib/mysql/mysql.sock
mysqli.default_socket = /var/lib/mysql/mysql.sock
pdo_mysql.default_socket = /var/lib/mysql/mysql.sock
Все настройки приведеные здесь абсолютно верны, решение проблемы ниже в комментариях.
2021.08.27
В новом обновлении файлы Битрикса конфликтуют со старыми версиями нашего решением.
Чтобы это исправить, мы доработали модуль Intec.Core.
Для восстановления работы сайта нужно обновить модуль Intec.Core через раздел админки Marketplace или вручную как описано ниже:
- Пройти по пути /bitrix/modules/intec.core/classes/
- Открыть файл Core.php
- Заменить его содержимое на код, представленный ниже
- Сохранить файл.
<?php
namespace intec;
require(__DIR__ . '/CoreBase.php');
use inteccoreCoreBase;
use inteccorediContainer;
use inteccorehelpersEncoding;
class Core extends CoreBase
{
}
spl_autoload_register(['intecCore', 'autoload'], true, true);
Core::$classes = require(__DIR__.'/classes.php');
Core::$container = new Container();
// global $DB;
$settingsDB = include($_SERVER["DOCUMENT_ROOT"]."/bitrix/.settings.php");
$settingsDB = $settingsDB["connections"]["value"]["default"];
$DBHostParts = explode(':', $settingsDB["host"]);
$DBHostAddress = $DBHostParts[0];
$DBHostPort = isset($DBHostParts[1]) ? $DBHostParts[1] : null;
(new corebaseApplication([
'id' => 'intec.core',
'basePath' => $_SERVER['DOCUMENT_ROOT'],
'charset' => Encoding::resolve(SITE_CHARSET),
'components' => [
'db' => [
'dsn' => 'mysql:host='.$DBHostAddress.';dbname='.$settingsDB["database"].(!empty($DBHostPort) ? ';port='.$DBHostPort : null),
'username' => $settingsDB["login"],
'password' => $settingsDB["password"],
'charset' => Encoding::resolve(SITE_CHARSET, Encoding::TYPE_DATABASE)
]
]
]));
unset($DBHostParts);
unset($DBHostAddress);
unset($DBHostPort);
Core::setAlias('@root/linked', dirname(dirname(dirname(dirname(__DIR__)))));
Core::setAlias('@bitrix', '@root'.BX_ROOT);
Core::setAlias('@upload', '@root/upload');
Core::setAlias('@modules', '@bitrix/modules');
Core::setAlias('@resources', '@bitrix/resources');
Core::setAlias('@templates', '@bitrix/templates');
Core::setAlias('@themes', '@bitrix/themes');
Core::setAlias('@intec/core/module', dirname(__DIR__));
Core::setAlias('@intec/core/libraries', '@intec/core/module/libraries');
Core::setAlias('@intec/core/resources', '@resources/'.Core::$app->id);
require(__DIR__.'/web.php');
Наши решения