Ошибка sqlstate hy000 1045 access denied for user

I want to set up and learn Laravel following this course

When I try to use the command php artisan migrate I get this error:

[IlluminateDatabaseQueryException]                                                                                                        
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO) (SQL: select * from information_schema.tables whe  
  re table_schema = laravel and table_name = migrations)

[PDOException]                                                                            
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO)

I have looked for answers. I figured I may have to make some changes in the .env file, but I don’t know what, and nothing I have tried so far has worked.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=

I’m using Ubuntu 16.04, not a Mac OS X as in the video, so I wonder what should I do differently? Is there some MySQL setting I did not set correctly?

David Buck's user avatar

David Buck

3,72335 gold badges31 silver badges35 bronze badges

asked Apr 2, 2017 at 14:02

MattSom's user avatar

3

I had the same problem with my plesk ubuntu 18.04 remote server. In your .env file put double quotes around your database password and username then run php artisan config:clear and php artisan cache:clear

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME="xyz"    
DB_PASSWORD="123"

I had never come across this problem before.

answered May 17, 2019 at 12:45

Mycodingproject's user avatar

MycodingprojectMycodingproject

1,0111 gold badge9 silver badges13 bronze badges

8

You don’t have a user named ‘laravel’.
You should change the DB_USERNAME to the one you’re actually using to access your DB.
Mostly it’s root by default so the changes in .env should be

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

answered Apr 3, 2017 at 8:26

Yassine Younes's user avatar

0

If you are trying to run this command with homestead, you need to make sure you change the values of the following environmental variables within the .env file to:

DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

After you have changed the values, make sure to run the following two commands before you do anything else:

php artisan config:clear
php artisan cache:clear

answered Dec 11, 2019 at 17:56

yusuf's user avatar

yusufyusuf

2412 silver badges2 bronze badges

3

if your DB_PASSWORD contains # symbol then enclose it like this

DB_PASSWORD="dfdf#523"

answered Apr 26, 2021 at 4:23

Ali Akbar Afridi's user avatar

0

In my case it solved with using localhost instead of 127.0.0.1

answered Jun 24, 2019 at 15:38

Pooria Honarmand's user avatar

Faced the same problem. Updated my root password in mysql using

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '.....'

where the updated password had no special character ‘#’. Updated it in the .env file. Then successfully ran php artisan migrate in the terminal.

answered Jan 14, 2020 at 11:26

MItrajyoti's user avatar

MItrajyotiMItrajyoti

4989 silver badges14 bronze badges

2

If you are using MAMP and the default root username/pw, your .env file database configuration should use ‘localhost’ instead of 127.0.0.1 and ‘root’ for BOTH the username and password:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

answered Feb 26, 2018 at 20:03

cschaefer's user avatar

cschaefercschaefer

2393 silver badges8 bronze badges

I had the same issue. What finally worked for me was performing Method 2 on this page.

Through my struggle, I learned that there are 4 different places where you can set a password for the root of the MySQL installation that comes with XAMPP. Setting the password in only 1 or 2 of these places alone is not enough. This is what I did to be able to perform my initial migration:

  1. In the Laravel .env file, in the DB_... section.
  2. In localhost:[your Apache port]/phpmyadmin, via User accounts -> root -> Edit privileges -> Change password.
  3. In localhost:[your Apache port]/phpmyadmin, via the method described in Method 2 on this page.
  4. In your config.inc.php file, which for me (on MacOS) was in /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php. This method is also described in Method 2 on this page.

And then restart MySQL and your web (Apache) server.

Be aware that after you successfully harmonize your passwords and try once again to migrate, you may get error output that looks almost the same as the Access Denied password error. However, this is a different error related to string lengths. See here for how to fix that issue.

answered Jul 17, 2018 at 19:55

Cameron Hudson's user avatar

Cameron HudsonCameron Hudson

3,0111 gold badge25 silver badges36 bronze badges

I had situation when server didn’t saw update .env file and php artisan cache:clear not help, but just was needed refresh server php artisan serve

answered Jul 13, 2018 at 12:15

dos4dev's user avatar

dos4devdos4dev

3912 gold badges9 silver badges25 bronze badges

If you are on MAMP, check your port number as well. Generally, it should look like this:

Host    localhost
Port    8889
User    root
Password    root
Socket  /Applications/MAMP/tmp/mysql/mysql.sock

baduker's user avatar

baduker

18.6k9 gold badges32 silver badges56 bronze badges

answered Mar 25, 2019 at 15:26

shivanisdev's user avatar

shivanisdevshivanisdev

6776 silver badges16 bronze badges

  1. Add a new user in phpmyadmin, eg. username-xyz, password-123

  2. Create a new database eg. dbname

  3. Update your .env file like this:

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=dbname
    DB_USERNAME=xyz    
    DB_PASSWORD=123
    
  4. Now clear your cache using php artisan cache:clear

  5. Finally, try migrating your tables with php artisan migrate

Run_Script's user avatar

Run_Script

2,4922 gold badges15 silver badges30 bronze badges

answered Jun 27, 2018 at 6:37

Ankit kumar's user avatar

When I had this issue, it was because I forgot my local environment was running mysql on a port other than 3306. For me, it was 3307. If you are using XAMPP, I would check what port you are using and make sure it matches your .env file.

answered Dec 27, 2017 at 20:26

Dan's user avatar

DanDan

8991 gold badge10 silver badges28 bronze badges

If you set the PHPMyAdmin password then you need to set something like on .ENV file

DB_CONNECTION=mysql
DB_PORT=3306
DB_HOST=localhost
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=root

If no password set then you can leave DB_PASSWORD as blank
DB_PASSWORD=

both are done still not work then it caches issue for fixing it you need to delete config file which is located to bootstart/cache/config.php
after that php artisan config: cache work and same file auto-generated

answered Aug 25, 2020 at 6:15

PHP Hupp Technologies's user avatar

For me the issue was fixed by adding » to the user and password fields like so:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=someCoolDatabaseName
DB_USERNAME='someCoolUsername'
DB_PASSWORD='someCoolPassword'

Make sure you are able to log in through your CMD with mysql -u root -p and getting in successfully.

answered Jun 29, 2021 at 1:35

Tim Bogdanov's user avatar

Did all the thigs and finally I surrounded username and password with quotes

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database
DB_USERNAME='username'
DB_PASSWORD='password'

answered Aug 18, 2021 at 15:29

Sampath Wijesinghe's user avatar

I solved this error by creating a new MySQL user and database. Open your terminal and do the following:

sudo mysql --user=root mysql

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Change the ‘username’ and ‘password’ to your preferred choices. Then grant privileges to this user.

GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' WITH GRANT OPTION;

FLUSH PRIVILEGES;

Finally, create the database;

CREATE DATABASE database_name;

Modify your .env file with the new credentials

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
DB_PASSWORD='password'

Hope it solves your problem.

answered Dec 13, 2022 at 18:29

Isaac Chambers's user avatar

If you’ve previously made databases on phpmyadmin with a different username and password, your local host account needs a new user to have a different password. I tried the username and password that I’ve used previously and that solved the problem for me.

answered Jul 15, 2018 at 6:57

D. O'Shea's user avatar

I also encountered the same error, you can refer here:

// config your host-name
APP_URL=http://test.demo

LOG_CHANNEL=stack

DB_CONNECTION=mysql
// default phpmyadmin display: localhost:3306
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root

answered Dec 16, 2019 at 15:13

congdc's user avatar

you can try this

DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

answered Dec 30, 2019 at 17:04

Mian Hamza's user avatar

For me I just add the password of my username in the .env file.

answered Feb 3, 2020 at 1:46

Joseph Tankoua's user avatar

I also had such problem. I created a new database by

CREATE DATABASE askiDB CHARACTER SET utf8;

Then in the navigator console of MySQL Workbench I selected this database and in the administrative roles tab selected all Roles. Then I set a password in the login tab.
Moreover, in .env file of the project I set the DB_USERNAME and DB_PASSWORD of this file correctly.
Then I execute the below command
php artisan migrate

and it worked fine.

answered Feb 15, 2020 at 17:28

M Shafaei N's user avatar

M Shafaei NM Shafaei N

3892 silver badges6 bronze badges

I was getting the same message and i found out the error was caused by incorrect credentials.

the following credential was getting error
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, ‘password’),

The correct credential below solved the problem.
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, »),

answered Nov 9, 2021 at 2:30

Eidul Ameen Sahul Hamid's user avatar

Laravel using Docker

1: Remove all images and volumes

./vendor/bin/sail down --rmi all -v 

2: Recreate the images and volumes

./vendor/bin/sail up 

There are many variations of solutions for this problem. I hope this one helps you.

answered Sep 22, 2021 at 23:25

13garth's user avatar

13garth13garth

6461 gold badge8 silver badges22 bronze badges

In My case i am using password contain «#» symbol , I have converted

DB_PASSWORD= "Special#"

Inside = «» It solves

answered Jun 1, 2022 at 7:26

MilanDulals's user avatar

You must create new file «.env» , copy contents from .env.example and past to .env, edit your paths, and wrtie php artisan migrate. This command run for me.

I have hard work, laravel 5.4 to 9.* :)

answered Feb 12 at 10:01

Grzegorz Mikina's user avatar

First run

mysql -u root -p

Then issue following queries:

CREATE DATABASE database_name;

CREATE USER 'user_name'@'%';

GRANT ALL PRIVILEGES  ON *.* TO 'user_name'@'%';

helvete's user avatar

helvete

2,42512 gold badges33 silver badges37 bronze badges

answered May 9 at 10:02

Manasse's user avatar

open config/database.php and add your password here:

'mysql' => [
...,
'password' => ''
...])

answered Mar 7, 2020 at 23:37

Mahdi Suissi's user avatar

Стандарт / от Автора / 18.06.2022 / 2 комментария /

3 способа РЕШЕНИЯ по исправлению ошибки mysqli real connect (): (HY000/1045): Access denied for user ‘username’@’localhost’ на сервере Centos 7 и VestaCP

Ошибка mysqli real connect (): (HY000/1045): Access denied for user ‘username’@’localhost’ очень часто возникает при обновлении версии PHP на веб сервере или самой базы данных,  особенно при использовании панели управления VestaCP.

Содержание:

Введение — ошибка mysql 1045

1 способ устранения ошибки mysql 1045

2 способ устранения ошибки mysql 1045

3 способ устранения ошибки mysql 1045

Заключение по устранению ошибки mysql 1045

Введение — ошибка mysql 1045

Прежде чем приступить к устранению данной ошибки, необходимо понять ряд элементарных вещей в работе базы данных MySQL.

Итак:

При создании пользователя базы данных MySQL учитывается 3 параметра, а не два. Первый параметр это username, имя пользователя базы данных, второй параметр, это имя хоста, под именем хоста подразумевается разрешение входа в базу, или с определенного IP адреса, или с определенного домена, или с любой машины кроме локальной, или только с локальной машины. Под локальной машиной подразумевается Ваш сервер, где расположена сама база данных и панель phpmyadmin.

Поясняю:

  • Пользователь например, root@localhost имеет имя root, свой пароль и право входить только с локальной машины, то есть с Вашего сервера через командную строку или панель управления.
  • Пользователь например, root@’мой домашний ip’ имеет имя root, свой пароль и право входить только с домашнего компьютера.
  • Пользователь например, root@’%’ имеет имя root, свой пароль и право входить с любого компьютера, кроме локального, то есть Вашей панели управления веб сервером.

Знак ‘%’ в одинарных кавычках указывает именно на право входить в базу с любого компьютера, кроме локальной машины.

Пользователей с именем root может быть два, три и более. Все эти пользователи будут иметь разные пароли и разные разрешения на вход с определенных хостов.

Ошибка mysqli-real-connect-hy000-1045

Ошибка mysqli-real-connect-hy000-1045

1 способ устранения ошибки mysql 1045

Ошибка 1045

ERROR 1045 (28000): Access denied for user ‘ root’@’localhost’ (using password: YES)

Самая распространенная и банальная ошибка это неправильная пара логина и пароля для входа в БД. Грубо говоря, Вы можете пытаться входить под пользователем root@’%’, вводя правильный никнейм и пароль через установленную на сервере панель  phpmyadmin. Но данный пользователь имеет право заходить с любого компьютера, кроме локальной машины. А панель phpmyadmin как раз является локальной машиной. Таким образом Вы будите получать данную ошибку.

Решение:

Самое простое, это попробовать ввести другой пароль от указанного пользователя. Но пароль может быть задан автоматически (в частности root), может быть пустым или просто утерянным.

Вам необходимо войти в MySQL через терминал в командной строке. Лично я использую программу putty, как и 99% администраторов веб сервера. Для того, чтобы попасть в БД, необходимо предварительно отредактировать конфигурационный файл под названием my.cnf. В операционной системе Centos 7 он находится /etc/my.cnf. Скачайте данный файл с сервера и вставьте в него после  такую строку: skip-grant-tables, должно получится примерно так:


[mysqld]
skip-grant-tables
другие параметры

Залейте файл с новыми параметрами на сервер, предварительно удалив старый, а лучше просто переименуйте старый файл. Перезапустите сервер БД через Вашу панель управления.

После редактирования выше указанного файла попасть в MySQL можно без пароля со всеми привилегиями.

Теперь откройте терминал и войдите под пользователем root без пароля, введя команду:


sudo mysql -u root

Далее введите команду:


SELECT user,host,password FROM mysql.user;
Если все сделали правильно, то будет показано вот такое окно:

Вход в базу данных без пароля

Вход в БД под root без пароля

Из таблицы видно, что пользователя root вообще НЕ существует, однако после правки выше указанного конфига, я без труда вошел под root и без пароля. Так же видно из таблицы, что присутствуют 2 пользователя — admin с паролями и доступом с локальной машины (непосредственно с сервера через панель phpmyadmin) и с любого домашнего компьютера через терминал.

Этих пользователей я создавал сам и пароли от них я знаю. Исходя из полученной информации, я могу без труда войти в панель phpmyadmin. И создать любого необходимого пользователя с любыми привилегиями (правами).

Пользователь root отсутствует по причине удаления. Я его просто удалил для написания данной статьи. У вас он скорей всего присутствует и таблица будет гораздо шире. Это просто мой тестовый сервер для экспериментов.

Давайте посмотрим еще один пример с другого сервера.

Вход в MariaDB без пароля

Список пользователей БД

По root у Вас будет примерно такая же картина. То есть один root имеет право войти в панель phpmyadmin с паролем. Один root имеет право на вход через терминал без пароля и т. д. Пароли в БД хранятся в зашифрованном виде.

Получив данную информацию, Вы сможете разобраться с доступами, найти необходимый пароль и войти в панель phpmyadmin.

НО увы, так бывает НЕ всегда!

2 способ устранения ошибки mysql 1045

Как уже писалось в начале статьи данная ошибка возникает после обновления ПО на сервере. И зачастую в панель phpmyadmin просто НЕ попасть. Если из первого раздела Вам не удалось разобраться с пользователями и паролями, то проще всего создать нового пользователя с правами администратора и войти в панель.

Выполнить это можно через терминал. Войдите на сервер через терминал с правами администратора и проверьте есть ли доступ без пароля. Как правило на сервере создается один пользователь root со входом без пароля из терминала.  Введите команду:


sudo mysql -u root

Если на сервер баз данных попасть не удалось, то отредактируйте файл (my.cnf), как рассказано в первом способе и повторите команду:


sudo mysql -u root

Теперь, когда в БД удалось попасть через терминал, необходимо создать нового пользователя с паролем и правами админа. Команда:


CREATE USER 'root'@'localhost' IDENTIFIED BY 'ЗДЕСЬ ПАРОЛЬ';

Следующей командой предоставляются права администратора:


GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;

После создания нового пользователя, как правило, можно под ним зайти в панель phpmyadmin. Это может быть совсем не обязательно пользователь root, а любой другой. Запомните имя пользователя и пароль, где то запишите себе. Лучше НЕ использовать root при создании нового пользователя.

Внимание!!! Не забудьте обратно отредактировать файл my.cnf, то есть удалить строку — skip-grant-tables.

3 способ устранения ошибки mysql 1045

Пожалуй, самый сложный способ, попытаюсь объяснить простым языком. Дело в том, что root пользователь создается по умолчанию. И если Вы начинаете играться с этим пользователем (root), то Вы нарушите пару логин — пароль. Так как пароль для этого пользователя создается и хранится в нескольких файлах на сервере.

Давайте поставим точку, рассмотрим все эти файлы и при необходимости зададим один пароль к данному юзеру.

Итак,

Файлов к счастью у нас не много, точнее три места которые необходимо проверить и поправить при необходимости.

  • Первое, открываем файл config.inc.php в Centos 7 находится /etc/phpmyadmin/config.inc.php В самый конец этого файла добавьте следующие строки кода:


/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = ' root';
$cfg['Servers'][$i]['controlpass'] = 'ЗДЕСЬ ПАРОЛЬ';

  • Второе, в файле /usr/local/vesta/conf/mysql.conf. Я использую панель управления VestaCP, если у Вас другая панель, то расположение файла будет отличатся. Откройте данный файл и посмотрите какой там указан пароль, если нужно, то смените на Ваш.
  • Третье, это непосредственно сама панель управления phpmyadmin.

Во всех трех местах, должны быть одинаковые пароли от этого юзера. Если не так, то исправляйте. В VestaCP при неправильных паролях в этих файлах может отвалится бэкап.

Заключение по устранению ошибки mysql 1045

Ошибка mysqli real connect 1045, как правило появляется при неправильной паре имя — пароль или после обновления ПО на сервере. Устраняется путем проверки пользователей через терминал и создания новых пользователей. В случаи не корректного пароля от root редактируются необходимые файлы.

P. S.

Я отлавливал все 3 причины сбоя панели управления phpmyadmin и данную статью публикую больше для себя как памятку по устранению неполадок. Но надеюсь Вам она тоже поможет. Оставляйте комментарии по решению данной проблемы.

Думаю, что теперь Вам не страшна ошибка mysqli_connect(): (HY000/1045): Access denied for user ‘username’@’localhost’.

Учебные материалы

Понравился материал? Подписывайтесь на наш блог. И получите бесплатный конструктор лендингов!

Только полезная информация и реальные кейсы

Ошибка: Access denied for user ‘root’@’localhost’ (Using password: YES и NO)

При работе с системой MySQL могут возникнуть самые разные ошибки, и на этапе освоения программы разобраться с ними может быть сложно. Одна из наиболее распространенных проблем — ошибка 1045, которая сопровождается сообщением Access denied for user ‘root’@’localhost’ (Using password: YES и NO). Сегодня я расскажу, как ее исправить.

Понять суть проблемы можно, переведя сообщение об ошибке на русский язык. Означает оно, что пользователю с именем root на машине localhost запрещен доступ к БД при использовании пароля или без него.

Окно Connection Error

Причины ошибки Access denied for user ‘root’@’localhost’

Чтобы свободно получить доступ в MySQL, должно совпасть три параметра, описывающих пользователя базы данных — имя, название машины и пароль. Если есть какие-то несовпадения, доступ будет запрещен. Самая простая причина проблемы — неправильный ввод пароля. Кроме этого, вызывать ошибку может неправильный синтаксис.

В системе MySQL нет простой зависимости имя пользователя – пароль, название хоста играет важную роль в получении доступа к БД. Оно может иметь вид IP-адреса, доменного имени, ключевого слова (например, localhost) или символа, объединяющего несколько машин в группу (например, % — любой хост, кроме локального).

Ошибка Access denied

Наиболее распространенные ошибки при обращении к БД:

  1. При присвоении прав новому пользователю не был указан адрес машины, с которой он может подключаться. В таком случае ему автоматически будет разрешено пользоваться БД с любого хоста, кроме локального, и при попытке подключения с localhost возникнет ошибка доступа.
  2. Неправильно расставленные кавычки. Если при создании пользователя написать ‘username@localhost’, это будет значить, что username@localhost может подключаться с любой машины, кроме локальной, а не что username может подключаться с компьютера localhost. Логин пользователя и имя машины должны иметь свою пару кавычек.
  3. Использование пароля при его отсутствии в базе данных.

В зависимости от того, при каком способе подключения к БД возникает ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO), используются разные методы решения проблемы.

Если ошибка Access denied for user появляется с указанием Using password: YES, проблема заключается в неправильном вводе пароля. Проверить это можно, открыв таблицу mysql.user, в которой хранятся данные обо всех пользователях.

Таблица USE Mysql

Порядок действий таков:

  1. Откройте таблицу пользователей.
  2. Проверьте, существует ли пользователь root с хостом localhost. Если он есть, смотрите на поле «password». Если там пусто, зайти в базу можно без ввода пароля. Если там что-то есть, значит, вы вводите неправильный пароль.
  3. Смените пароль командой SET PASSWORD.
  4. Если пользователя root нет, создайте его, установите пароль и предоставьте ему права.

После этого в базу данных можно зайти. Если изменить данные не получается, следует использовать параметр —skip-grant-tables, который отменяет все настройки разрешений.

Файл конфигурации

Строки, которые нужно изменить в файле конфигурации

Если ошибка появляется с ключом (Using password: NO), нужно сделать следующее изменить файл config.inc.php, указав в нем правильные данные. Если проблема возникает при установке MySQL, нужно удалить базы данных старой версии программы или сменить пароль для доступа к ним, используя режим —skip-grant-tables.

Таким образом, ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO) возникает при несоответствии пароля и имени пользователя и легко исправляется заменой данных для входа.

Опубликовано 06.06.2017 Обновлено 28.04.2021

Table of Contents

  • Introduction
  • Causes of SQLState[HY000] [1045] Error
  • Step-by-step Solution
  • Step 1: Verify Database Credentials
  • Step 2: Grant Proper Privileges
  • Step 3: Check Host Address
  • Step 4: Configure Firewall Settings
  • Step 5: Restart MySQL Server
  • FAQ
  • Related Links

Introduction

SQLState[HY000] [1045] is a common error in MySQL databases that occurs when a client is unable to establish a connection to the database server. This error is typically accompanied by the message «Access denied for user ‘username’@’host’ (using password: YES/NO).» In this guide, we will discuss the possible causes of this error and provide a step-by-step solution to resolve it.

Causes of SQLState[HY000] [1045] Error

There are several possible causes for the SQLState[HY000] [1045] error:

  1. Incorrect database credentials (username or password)
  2. Insufficient privileges for the user connecting to the database
  3. Incorrect host address specified for the connection
  4. Firewall settings blocking the connection
  5. MySQL server not running or not accepting connections

Step-by-step Solution

To resolve the SQLState[HY000] [1045] error, follow these steps:

Step 1: Verify Database Credentials

Ensure that the username and password you are using to connect to the MySQL server are correct. You can find the database credentials in your application’s configuration file or in the MySQL server’s user table. To check the credentials, log in to the MySQL server using the command line:

mysql -u username -p

Enter the password when prompted. If you can successfully log in, the credentials are correct. If you still receive the error, proceed to the next step.

Step 2: Grant Proper Privileges

Make sure the user connecting to the database has the necessary privileges. Log in to the MySQL server as the root user and grant the required privileges to the user:

GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'host' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

Replace database_name, username, host, and password with the appropriate values. If the user still cannot connect, proceed to the next step.

Step 3: Check Host Address

Ensure the host address specified in your application’s configuration file matches the host address in the MySQL server’s user table. The host address can be a domain name, IP address, or ‘localhost’ for connections from the same machine as the server.

To check the host address for a user, log in to the MySQL server and run the following query:

SELECT host FROM mysql.user WHERE user = 'username';

Replace username with the appropriate value. If the host address does not match, update it in your application’s configuration file or change the user’s host address in the MySQL server.

Step 4: Configure Firewall Settings

If the SQLState[HY000] [1045] error persists, check your firewall settings to ensure that the connection is not being blocked. Add a rule to allow traffic to the MySQL server’s port (default is 3306) from the client’s IP address.

Refer to your firewall’s documentation for instructions on how to add a rule.

Step 5: Restart MySQL Server

Finally, if the error still occurs, restart the MySQL server to ensure that it is running and accepting connections:

On Linux:

sudo systemctl restart mysqld

On Windows:

net stop MySQL
net start MySQL

FAQ

Q1: What is the default port for MySQL?

The default port for MySQL is 3306.

Q2: How do I change the MySQL server’s port?

To change the MySQL server’s port, edit the my.cnf (Linux) or my.ini (Windows) configuration file and set the port directive to the desired value. Restart the MySQL server for the changes to take effect.

Q3: Can I have multiple users with the same username but different host addresses?

Yes, you can have multiple users with the same username but different host addresses. MySQL treats these as distinct users with separate privileges.

Q4: How do I reset the root password in MySQL?

To reset the root password in MySQL, follow these steps:

  1. Stop the MySQL server
  2. Restart the server with the --skip-grant-tables option
  3. Log in to the server without a password
  4. Update the mysql.user table with the new password
  5. Restart the server without the --skip-grant-tables option

Refer to the official MySQL documentation for detailed instructions.

Q5: How do I create a new MySQL user?

To create a new MySQL user, log in to the MySQL server and run the following query:

CREATE USER 'username'@'host' IDENTIFIED BY 'password';

Replace username, host, and password with the appropriate values. Grant the necessary privileges to the new user as described in Step 2 of this guide.

  1. MySQL Official Documentation
  2. Managing MySQL Users and Privileges
  3. Troubleshooting MySQL Connection Issues
  4. Resetting the MySQL Root Password

Здравствуйте, наткнулся у себя на вот такую ошибку, пароль, хост, юзер, имя бд все верно. Запрос sql так же верен(протестил в бд).

Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000] [1045] Access denied for user »@’localhost’ (using password: NO)’ in D:ServerOpenServerdomainse-shopper.ruappcomponentsdb.php:8 Stack trace: #0 D:ServerOpenServerdomainse-shopper.ruappcomponentsdb.php(8): PDO->__construct(‘mysql:host=;dbn…’, NULL, NULL) #1 D:ServerOpenServerdomainse-shopper.ruappmodelsProduct.php(9): Db::getConnection() #2 D:ServerOpenServerdomainse-shopper.ruappcontrollersSiteController.php(11): Product::getLatestProducts(6) #3 [internal function]: SiteController->actionIndex() #4 D:ServerOpenServerdomainse-shopper.ruappcomponentsroute.php(41): call_user_func_array(Array, Array) #5 D:ServerOpenServerdomainse-shopper.ruindex.php(6): Router->run() #6 {main} thrown in D:ServerOpenServerdomainse-shopper.ruappcomponentsdb.php on line 8

$sql = 'SELECT `id`, `name`, price, is_new FROM product '
               . 'WHERE status = "1" ORDER BY id DESC '
               . 'LIMIT :count';
        $result = $db->prepare($sql) or die('Не соединения с бд!');
        $result->bindParam(':count', $count, PDO::PARAM_INT);
        $result->setFetchMode(PDO::FETCH_ASSOC);
        $result->execute();

Заранее, спасибо за ответ

Понравилась статья? Поделить с друзьями:
  • Ошибка sqlstate 23000 integrity constraint violation
  • Ошибка sqlserver 15404 не удалось получить сведения о пользователе
  • Ошибка sqllib системная таблица sysaltfiles в экземпляре sql server
  • Ошибка sqlallochandle для драйвера в sql handle dbc
  • Ошибка sql указанный sql server не найден