Ubuntu phpmyadmin error 1045

I'm trying to install queXS cati app on my Ubuntu desktop and I installed MySQL server and PHP 5 and I cannot login into MySQL server as root without password: mysql -u root it says ERROR 1045(...

I’m trying to install queXS cati app on my Ubuntu desktop and I installed MySQL server and PHP 5 and I cannot login into MySQL server as root without password:

mysql -u root 

it says

ERROR 1045(28000) : Access denied for user 'root@localhost' (using password: no )

But it’s okay when I enter mysql -u root -p

I can’t figure out what the problem is.

oerdnj's user avatar

oerdnj

7,88038 silver badges49 bronze badges

asked Jan 7, 2014 at 10:42

user232705's user avatar

1

Add switch -p for password based login:

mysql -u root -p

That is the normal behaviour. You set a root password for your database so from now on you can’t access it without password. That is why it reports:

Access denied for user ‘root@localhost’ (using password: no )

Obviously when you give the password with the -p switch you succeed.

pocket-full-of-quarters's user avatar

answered Jan 7, 2014 at 10:47

falconer's user avatar

falconerfalconer

14.7k3 gold badges45 silver badges66 bronze badges

In simple words your «root» session does not know the password of the mysql root user.

If you want to make it easier to access your mysql, create a file .my.cnf in /root/ with these lines:

[mysqladmin]
 user = root
 password = mysqlrootpassword
[mysql]
 user = root
 password = mysqlrootpassword
[mysqldump]
 user = root
 password = mysqlrootpassword

where of course mysqlrootpassword is your password for mysql’s root password. When you execute mysql it uses this password.

Attend to the safety of this file — give it secure rights, so that nobody on your server can read it!

Zanna's user avatar

Zanna

68.2k55 gold badges210 silver badges320 bronze badges

answered Jan 16, 2014 at 22:25

pl_'s user avatar

2

Login to webmin and under servers, access the mySQLdatabase server.You will then be able to set the (user) password provided you have:

mysql -u (**user**) -p < /usr/share/doc/rsyslog-mysql-5.8.10/createDB.sql.

The web gui is easy but to be secure use the terminal.

cheers.

Charles Green's user avatar

answered Sep 24, 2014 at 12:36

SLAYER_FIFA15's user avatar

1

Everyone wants to make database changes in just one click.

That’s why, phpMyAdmin becomes an inevitable tool for website owners.

However, phpMyAdmin can sometimes show weird errors which are difficult to tackle. One such problem is “Error 1045 in phpMyAdmin“.

At Bobcares, we help server owners resolve these errors as part of our Dedicated Support Services.

Today, let’s discuss the top 2 reasons for this error and how we fix them.

phpMyAdmin error 1045 – A Brief Explanation

Before we move on to the reasons, let’s first get a brief idea of this error.

Customer’s usually see this error when they try to access phpMyAdmin to manage the databases. For instance, users see the following error in the phpMyAdmin interface.

phpmyadmin error 1045

phpMyAdmin error #1045

This means that phpMyAdmin tried to connect to the MySQL server, but the server rejected the connection.

phpMyAdmin error 1045 – Causes & Solutions

Now, let’s see the common reasons for this error and how our Support Engineers fix them.

1) Incorrect password

This is the one of the most common reasons for the phpMyAdmin error 1045. A typo in the username or password while accessing the phpMyAdmin panel results in this error.

Similarly, we’ve seen instances where customers reset the MySQL root password or MySQL user password, but forget to update the changes in the phpMyAdmin configuration. This can also create problems.

Solution

Firstly, our Support Engineers get the MySQL username and password from the customer. We then use the below command to access the MySQL server from console.

mysql -u user -ppassword

Replace user with MySQL username and password with MySQL password.

If the logins work, the next step is to check whether these logins are working for phpMyAdmin. If not, we can make sure that these logins are not updated in the phpMyAdmin configuration.

So, our Database Experts access the phpMyAdmin configuration file and add the correct username and password in the config.inc.php file.

For example, on a local WAMP server, the location of config.inc.php will be C:wampappsphpmyadminx.x.x. Similarly, on Plesk servers, this location will be /usr/local/psa/admin/htdocs/domains/databases/phpMyAdmin/libraries/config.default.php.

Here, our Support Experts modify the following parameters and ensure that correct username and password is used.

$cfg['Servers'][$i]['user'] = 'root'; //MySQL user
$cfg['Servers'][$i]['password'] = ''; // MySQL password

In some cases, we change auth_type parameter for the logins to work.

$cfg['Servers'][$i]['auth_type'] = 'cookie'

Finally, we clear the browser cookies to refresh the data.

On the other hand, if the MySQL logins doesn’t work, we reset the MySQL user password and update the new one in the phpMyAdmin configuration.

For example, in cPanel servers, we reset the user password from Databases > MySQL Databases > Current Users. Similarly, we reset the MySQL root password after starting the MySQL in safe mode.

UPDATE mysql.user SET Password=PASSWORD("EnterYourPasswordHere") WHERE User="root";
FLUSH PRIVILEGES;

2) Insufficient privileges

Similarly, another common reason for this error is the insufficient privileges for the database user that’s trying to connect to the database. For example, customers receive an error like below.

#1045 - Access denied for user 'user'@'localhost' (using password: YES)

This means that the database user ‘user‘ is not permitted to access the database.

Solution

Now, let’s see what our Support Engineers do in these cases.

Here, we make sure that proper privileges are given for the user to access the database. For example, we assign proper privileges to the database user using the below command.

GRANT ALL PRIVILEGES ON *.* TO user@'localhost' IDENTIFIED BY 'password' with grant option;

This will grant all privileges to the database user ‘user‘ on the selected database. Later, we save these privileges using the below command.

FLUSH PRIVILEGES;

Likewise on cPanel servers, we change the privileges of the user from cPanel > Mysql databases > Current databases > Privileged users > Click on the database user.

[Need an Expert to fix this MySQL error on your server? Click here and get one of our Database Experts to fix it for you.]

Conclusion

In short, phpMyAdmin error 1045 occurs mainly due to typo errors in MySQL username or password, insufficient privileges of the database user and so on. Today, we’ve discussed the top 2 reasons for this error and how our Dedicated Support Engineers fix them.

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»;

This is a very common issue whenever a user installs and configures a new MySQL. Then user has to face the problem, Which is Can’t log into phpMyAdmin: mysqli_real_connect(): (HY000/1698): Access denied for user ‘root’@’localhost’. This error message usually appears for new installations of MySQL when you try to login in PHPmyadmin with the root user.

But in this tutorial, you have been given a very easy solution. This will solve the problem “access denied for user ”@’localhost’ to database phpmyadmin’”.

This mysqli::real_connect(): (hy000/1045): access denied for user ‘root’@’localhost’ (using password: yes/no) tutorial guide will show you how to quickly resolve the access denied for user ‘root’@’localhost’ (using password yes) mysql phpmyadmin ubuntu 16/18/20.04. The outlined instructions apply to both MySQL and MariaDB. There will be no need to modify any tables or to perform complex configurations.

Prerequisites for access denied for user ‘root’@’localhost’ (using password yes) mysql phpmyadmin ubuntu 18.04/20.04 :

  • Access to a command line or terminal
  • MySQL or MariaDB installed
  • User with sudo or root privileges

Step 1 – Login as Root user MySQL

Installed MySQL and try to access phpmyadmin on the local/server machine with the root user, the command you use is:

mysql -u root -p

In most cases, you will receive the error message Access denied for user ‘root’@’localhost’.

You can enable access for root using one MySQL command.

To be able to log into MySQL as root, first use sudo to modify the root user:

sudo mysql

Enter your password at the prompt. A MySQL shell loads.

Use the ALTER USER command and change the authentication method to log into MySQL as root:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'insert_password';

This command changes the password for the user root and sets the authentication method to mysql_native_password. This is a traditional method for authentication, and it is not as secure as auth_plugin. In the example above, we set “root” as the password, but we encourage you to set a stronger password.

 mysql> FLUSH PRIVILEGES; 

Step 2 – Restart Apache Server

You need to restart Apache 2 server by using the following command:

sudo service apache2 restart

Step 3 – Test Root MySQL User For Access PHPMyadmin

Finally, you can login as root from phpMyAdmin. So, open your browser and type the below url with your ec2 server ip:

http://[SERVER_PUBLIC_IP]/phpmyadmin

Then you will look like on your browser:

Conclusion

In this tutorial, you have learned how to solve access denied for user ‘root’@’localhost’ (using password yes) mysql phpmyadmin ubuntu 18.04/20.04.

Recommended Linux/Ubuntu Tutorials

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

View all posts by Admin

Дата: 25.11.2013

Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

Статистика форума SQLinfo показывает, что одной из наиболее популярных проблем является ошибка mysql №1045 (ошибка доступа).
Текст ошибки содержит имя пользователя, которому отказано в доступе, компьютер, с которого производилось подключение, а также ключевое слово YES или NO, которые показывают использовался ли при этом пароль или была попытка выполнить подключение с пустым паролем.

Типичные примеры:

ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) — сервер MySQL
— сообщает, что была неудачная попытка подключения с локальной машины пользователя с именем root и
— не пустым паролем.

ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем root при попытке подключения с пустым паролем.

ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем ODBC при попытке подключения с пустым паролем.

Причина возникновения ошибки 1045

Как ни банально, но единственная причина это неправильная комбинация пользователя и пароля. Обратите внимание, речь идет о комбинации пользователь и пароль, а не имя пользователя и пароль. Это очень важный момент, так как в MySQL пользователь характеризуется двумя параметрами: именем и хостом, с которого он может обращаться. Синтаксически записывается как ‘имя пользователя’@’имя хоста’.

Таким образом, причина возникновения MySQL error 1045 — неправильная комбинация трех параметров: имени пользователя, хоста и пароля.

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

Замечание: Важно понимать, что в базе не существует просто пользователя с заданным именем (например, root), а существует или пользователь с именем root, имеющий право подключаться с заданного хоста (например, root@localhost) или даже несколько разных пользователей с именем root (root@127.0.0.1, root@webew.ru, root@’мой домашний ip’ и т.д.) каждый со своим паролем и правами.

Примеры.
1) Если вы не указали в явном виде имя хоста

GRANT ALL ON publications.* TO ‘ODBC’ IDENTIFIED BY ‘newpass’;

то у вас будет создан пользователь ‘ODBC’@’%’ и при попытке подключения с локальной машины вы получите ошибку:

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

так как пользователя ‘ODBC’@’localhost’ у вас не существует.

2) Другой первопричиной ошибки mysql 1045 может быть неправильное использование кавычек.

CREATE USER ‘new_user@localhost’ IDENTIFIED BY ‘mypass’; — будет создан пользователь ‘new_user@localhost’@’%’

Правильно имя пользователя и хоста нужно заключать в кавычки отдельно, т.е. ‘имя пользователя’@’имя хоста’

3) Неочевидный вариант. IP адрес 127.0.0.1 в имени хоста соответствует ключевому слову localhost. С одной стороны, root@localhost и ‘root’@’127.0.0.1’ это синонимы, с другой, можно создать двух пользователей с разными паролями. И при подключении будет выбран тот, который распологается в таблице привелегий (mysql.user) раньше.

4) Аккаунт с пустым именем пользователя трактуется сервером MySQL как анонимный, т.е. позволяет подключаться пользователю с произвольным именем или без указания имени.
Например, вы создали пользователя »@localhost с пустым паролем, чтобы каждый мог подключиться к базе. Однако, если при подключении вы укажите пароль отличный от пустого, то получите ошибку 1045. Как говорилось ранее, нужно совпадение трех параметров: имени пользователя, хоста и пароля, а пароль в данном случае не совпадает с тем, что в базе.

Что делать?

Во-первых, нужно убедиться, что вы используете правильные имя пользователя и пароль. Для этого нужно подключиться к MySQL с правами администратора (если ошибка 1045 не дает такой возможности, то нужно перезапустить сервер MySQL в режиме —skip-grant-tables), посмотреть содержимое таблицы user служебной базы mysql, в которой хранится информация о пользователях, и при необходимости отредактировать её.

Пример.

SELECT user,host,password FROM mysql.user;
+—————+——————+——————————————-+
| user          | host            | password                                  |
+—————+——————+——————————————-+
| root          | house-f26710394 | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| aa            | localhost       | *196BDEDE2AE4F84CA44C47D54D78478C7E2BD7B7 |
| test          | localhost       |                                           |
| new_user      | %               |                                           |
|               | %               | *D7D6F58029EDE62070BA204436DE23AC54D8BD8A |
| new@localhost | %               | *ADD102DFD6933E93BCAD95E311360EC45494AA6E |
| root          | localhost       | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
+—————+——————+——————————————-+

Если изначально была ошибка:

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

    значит вы указывали при подключении неверный пароль, так как пользователь root@localhost существует. Сам пароль храниться в зашифрованном виде и его нельзя узнать, можно лишь задать новый

    SET PASSWORD FOR root@localhost=PASSWORD(‘новый пароль’);

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

    в данном случае в таблице привилегий отсутствует пользователь ‘ODBC’@’localhost’. Его нужно создать, используя команды GRANT, CREATE USER и SET PASSWORD.

Экзотический пример. Устанавливаете новый пароль для root@localhost в режиме —skip-grant-tables, однако после перезагрузки сервера по прежнему возникает ошибка при подключении через консольный клиент:
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)
Оказалось, что было установлено два сервера MySQL, настроенных на один порт.

phpmyadmin

При открытии в браузере phpmyadmin получаете сообщение:

Error
MySQL said:

#1045 — Access denied for user ‘root’@’localhost’ (using password: NO)
Connection for controluser as defined in your configuration failed.
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.

Ни логина, ни пароля вы не вводили, да и пхпадмин их нигде требовал, сразу выдавая сообщение об ошибке. Причина в том, что данные для авторизации берутся из конфигурационного файла config.inc.php Необходимо заменить в нем строчки

$cfg[‘Servers’][$i][‘user’] = ‘root’;      // MySQL user
$cfg[‘Servers’][$i][‘password’] = »;      // MySQL password (only needed

на

$cfg[‘Servers’][$i][‘user’] = ‘ЛОГИН’;      
$cfg[‘Servers’][$i][‘password’] = ‘ПАРОЛЬ’

Установка новой версии

Устанавливаете новую версию MySQL, но в конце при завершении конфигурации выпадает ошибка:

ERROR Nr. 1045
Access denied for user ‘root’@‘localhost’ (using password: NO)

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

P.S. Статья написана по материалам форума SQLinfo, т.е. в ней описаны не все потенциально возможные случаи возникновения ошибки mysql №1045, а только те, что обсуждались на форуме. Если ваш случай не рассмотрен в статье, то задавайте вопрос на форуме SQLinfo
Вам ответят, а статья будет расширена.

Дата публикации: 25.11.2013

© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

  • Печать

Страницы: [1] 2  Все   Вниз

Тема: PhpMyAdmin #1045 Невозможно подключиться к серверу MySQL  (Прочитано 144873 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
Bling-Bling

Не могу разобраться почему почему не пускает в PhpMyAdmin, ошибка #1045 Невозможно подключиться к серверу MySQL.
Подскажите где в конфигах посмотреть пользователя и пароль на вход в PhpMyAdmin?


Оффлайн
gregory5

« Последнее редактирование: 24 Февраля 2011, 14:25:15 от gregory5 »


Оффлайн
Bling-Bling

ЭЭэээ…. дело в том что гуглил и это читал.
После ввода пароля проваливаюсь в пустую страничку  

а если пароль ввести не верно, то получаю ошибку  #1045 Невозможно подключиться к серверу MySQL

через консоль в mysql пускает

« Последнее редактирование: 24 Февраля 2011, 17:24:12 от Bling-Bling »

 10.10


Оффлайн
geka_ubuntu

После установки mysql — подключитесь к серверу:

mysql -u root

в терминале отобразится сообщение:

Welcome…

установите пароль на root (например — 000000):

set password for root@localhost=password(‘000000’);

после загрузите PhpMyAdmin и введите соответствующие логин и пароль…

дело в том что PhpMyAdmin — не разрешает вход без пароля

« Последнее редактирование: 05 Марта 2011, 16:07:35 от geka_ubuntu »


Оффлайн
pashulka

***@***:~$ sudo mysql -u root
Вывод:

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

А в таком случае что делать?


Оффлайн
drako


Оффлайн
AnrDaemon

mysql -u root -p

Топик читать пробовал?

ЭЭэээ…. дело в том что гуглил и это читал.
После ввода пароля проваливаюсь в пустую страничку 

а если пароль ввести не верно, то получаю ошибку  #1045 Невозможно подключиться к серверу MySQL

через консоль в mysql пускает

Была такая проблема… версия PMA какая?

Хотите получить помощь? Потрудитесь представить запрошенную информацию в полном объёме.

Прежде чем [Отправить], нажми [Просмотр] и прочти собственное сообщение. Сам-то понял, что написал?…


Оффлайн
VinnyPooh

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


Оффлайн
sssats

Возможно пригодится кому-то в будущем. Такая-же проблема была. Оказалось что когда вводил пароль в консоли ввел на русском, на консоль восприняла как «????» поэтому в web-морду не могло зайти ни русскими не английскими. Через консоль вошел ввоодя на русском и сменил пароль.


Оффлайн
bumctik

mysql -u root -p

что делать если даже после того как пароль вводишь и жмешь Enter
все равно терминал возвращает

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

===========================================================
Пользователи убунты не знают о существовании других дистров.
Они считают, что Ubuntu — это и есть линукс, единственный и неповторимый.


Оффлайн
fisher74

Вспоминать правильный пароль мускульного root-а. Если не вспоминается — «сбрасывать».


Оффлайн
bumctik

Вспоминать правильный пароль мускульного root-а. Если не вспоминается — «сбрасывать».

проблема в том, что я не могу забыть только что установленный (при установке) пароль на MYSQl
тут видимо проблема в другом, есть какой-то баг

и как сбросить пароль root?

===========================================================
Пользователи убунты не знают о существовании других дистров.
Они считают, что Ubuntu — это и есть линукс, единственный и неповторимый.


Оффлайн
fisher74

и как сбросить пароль root?

Примерно так

sudo service mysqld stop
/usr/bin/mysqld_safe --skip-grant-tables --user=root &
mysql -u root
UPDATE mysql.user SET Password=PASSWORD('newpassword') WHERE User='root';
FLUSH PRIVILEGES;
q
sudo service mysqld restart


Оффлайн
bumctik

да это все пробовал все равно не помогло…полностью снес все под 0 и заново поставил, и заработало (LAMP) из коробки

===========================================================
Пользователи убунты не знают о существовании других дистров.
Они считают, что Ubuntu — это и есть линукс, единственный и неповторимый.


mirzayaky

 #2002 Невозможно подключиться к серверу MySQL

aleksandr@aleksandr-laptop:~$ sudo service mysqld stop
[sudo] password for aleksandr:
mysqld: unrecognized service
aleksandr@aleksandr-laptop:~$ /usr/bin/mysqld_safe --skip-grant-tables --user=root &
[1] 6073
aleksandr@aleksandr-laptop:~$ 131109 16:32:15 mysqld_safe Can't log to error log and syslog at the same time.  Remove all --log-error configuration options for --syslog to take effect.
131109 16:32:15 mysqld_safe Logging to '/var/log/mysql/error.log'.
131109 16:32:15 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
/usr/bin/mysqld_safe: 126: /usr/bin/mysqld_safe: cannot create /var/log/mysql/error.log: Permission denied
/usr/bin/mysqld_safe: 1: eval: cannot create /var/log/mysql/error.log: Permission denied
131109 16:32:15 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
/usr/bin/mysqld_safe: 126: /usr/bin/mysqld_safe: cannot create /var/log/mysql/error.log: Permission denied

[1]+  Выход из 2       /usr/bin/mysqld_safe --skip-grant-tables --user=root
aleksandr@aleksandr-laptop:~$ mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
aleksandr@aleksandr-laptop:~$ UPDATE mysql.user SET Password=PASSWORD('newpassword') WHERE User='root';
bash: ошибка синтаксиса около неожиданной лексемы `('
aleksandr@aleksandr-laptop:~$


  • Печать

Страницы: [1] 2  Все   Вверх

Понравилась статья? Поделить с друзьями:
  • Ubuntu network is unreachable как исправить
  • Ubuntu mysql error log
  • Udma crc error count как сбросить
  • Udma crc error count как исправить
  • Udma crc error count synology