- 贵哥的编程之路
- 文章来自专栏
- 用户7873631的专栏
- Toplam 1 Cevap
- Kullanıcı hakkında ihlal bildir:
- Answer
- Solution:
- Share
- Didn’t find the answer?
- Similar questions
- Step 1 – Login as Root user MySQL
- Step 2 – Restart Apache Server
- Conclusion
- Recommended Linux/Ubuntu Tutorials
- Post navigation
- Ошибка [1045] при подключении к БД в Yii2
- Re: Ошибка [1045] при подключении к БД в Yii2
- Re: Ошибка [1045] при подслючении к БД в Yii2
- Re: Ошибка [1045] при подключении к БД в Yii2
- Re: Ошибка [1045] при подключении к БД в Yii2
- Re: Ошибка [1045] при подключении к БД в Yii2
- Solution 1: Sudo then Change Password
- Conclusion
- Introduction
- Understanding MySQL Users and Hosts
- Changing a MySQL User’s Host Value
- Via Command Line
- Via phpMyAdmin
- Solution 1: Run artisan command
- Solution 2: Set Database Credentials in this way
- Solution 3: delete bootstrap/cache
- Conclusion
- ‘SQL error 1045 sqlstate 28000’ – What this means?
- ‘SQL error 1045 sqlstate 28000’ – Causes & Fixes
- 1) Typo in username and password
- Solution
- 2) Accessing from wrong host
- Solution
- 3) User doesn’t exist
- Solution
- 4) Existence of Anonymous users
- Solution
- 5) Insufficient privileges
- Solution
- MySQL 1045 error Access Denied triggers in the following cases
- 1) Connecting to wrong host:
- 2) User does not exist:
- 3) User exists but client host does not have permission to connect:
- 4) Password is wrong, or the user forgot his password:
- 5) Special characters in the password being converted by Bash:
- 6) SSL is required but the client is not using it:
- 7) PAM backend not working:
- Создание нового пользователя при ошибке HY000/1045
- Связанные статьи
- Answer
- Форум
- User Error in connection to db Mysql
贵哥的编程之路
735 篇文章
2021-08-31 16:12:37阅读 3730
你的database.php文件中改数据库名+用户名+密码就行了哈.
本文参与 腾讯云自媒体分享计划 ,欢迎热爱写作的你一起参与!
本文分享自作者个人站点/博客
https://blog.csdn.net/qq_37805832
复制
如有侵权,请联系 cloudcommunity@tencent.com 删除。
展开阅读全文
文章来自专栏
用户7873631的专栏
735 篇文章
32 人关注
评论 (
0
)
写评论
相关文章
长按识别或截图保存关注腾讯云开发者
Copyright © 2013-2022Tencent Cloud. All Rights Reserved.腾讯云 版权所有
I keep getting the error message above after completing a PHP tutoria for «booking application» at startutorial.com. I can’t get past the error message shown above (and below). I created the files on Debian 11.2, with Apache2, MySQL 7.4, and PHP. Help appreciated.
Server errors are annoying, especially when they are cryptic like “sql error 1045 sqlstate 28000″.
The message contains some error codes.
But, what’s the real problem here?
At Bobcares, we help website owners resolve complex errors like “sql error 1045 sqlstate 28000“ as part of our Outsourced Hosting Support services.
Today, let’s discuss the top 5 reasons for this error and we fix them.
I recently tried to login into my MariaDB database via shell and got this error even though I’m 100% sure the password is correct:
mysql -u root -p
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I’m running a node.js server that connects to the same database with the same password with no problems…
RiggsFolly
90.3k20 gold badges100 silver badges144 bronze badges
asked May 3 at 6:33
2
You don’t have privileges to connect to the root
mysql user. Simply use sudo
:
sudo mysql -u root -p
Enter password that you use on your machine, after that enter password to the root
mysql user.
answered Jun 21 at 20:27
How do I make it so when I put it to type «cookie», it will accept the config.inc values?
That’s not how ‘cookie’ authentication works, it doesn’t read the ‘user’ and ‘password’ fields from config.inc.php
because you’re prompted for them when you connect. WAMP, at least last time I checked, uses the ‘config’ auth_type setting, which does use the ‘user’ and ‘password’ that are hardcoded in the configuration.
Your configuration looks okay to me, in particular the use of host ‘localhost’ matches with the hostname of the user that exists in the screenshot, which is a common problem people often encounter (trying to connect via ‘127.0.0.1’ to an account with host field ‘localhost’).
We did recently make some changes to code that handled «special characters» in passwords, would you mind downloading an older version and seeing if you’re able to connect successfully? Version 5.0.0 can be downloaded from https://www.phpmyadmin.net/files/5.0.0/
When I try to run my php code on localhost, then error given given below appears:
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO) in C:\xampp\htdocs\Final Project CSE-391\project\config.php:2 Stack trace: #0 C:\xampp\htdocs\Final Project CSE-391\project\config.php(2): PDO->__construct(‘mysql:host=loca…’, ‘root’, ») #1 C:\xampp\htdocs\Final Project CSE-391\project\index.php(2): include(‘C:\xampp\htdocs…’) #2 {main} thrown in C:\xampp\htdocs\Final Project CSE-391\project\config.php on line 2strong text
I need suggestion to solve this issue.
asked Apr 25 at 22:59
1
This is a wrong credential issue. Check the values you used on the browser to log into PHPMyAdmin
to ensure it is correct before putting it in the connection config.
You could have entered the wrong password or leaving password to blank after having set a password.
answered Apr 26 at 11:29
David KariukiDavid Kariuki
1,2681 gold badge13 silver badges29 bronze badges
Merhaba,
Bir PHP Script’i indirdim. Fakat localhost’ta çalıştırmak istediğimde
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)
Hatası alıyorum. Ne yapabilirim?
Wamp kullanıyorum
@alattin
Toplam 1 Cevap
SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: YES) hatası kullandığın script MYSQL’e bağlanamıyor demek. Bağlanamama sebebi script’in kullandığı kullanıcı adı ve parola ikilisi sendeki MYSQL veritabanındaki ile uyuşmuyor. Daha basitçe parola hatalı.
- @alattin abi dosyalardan falan şifrelerin hepsini düzenledim fakat hala aynı toprak34 3 yıl önce
- sen script içinde tanımladığın kullanıcı adı ve parola ile MY SQL’e giriş yapabiliryor musun @toprak ? alattin 3 yıl önce
üyelik gerektirir
Cevap yazabilmek için üye girişi yapmalısınız.
Eğer uzmanim.net üyesiyseniz giriş yapabilirsiniz: üye girişi yap uzmanim.net’e üye olmak çok kolaydır: hemen kayıt ol
Kullanıcı hakkında ihlal bildir:
Lütfen aşağıdaki kutuya şikayetinizin detaylarını yazın. Şikayetinizi değerlendirildikten sonra size bilgi vereceğiz.
274 votes
1 answers
Get the solution ↓↓↓
I’m installing Laravel homestead for the first time and have been stuck with the above issue and haven’t been able to resolve it. The above issue arises when I execute the php artisan migrate:fresh —seed command in my Mac terminal after executing vagrant ssh and cd code. I have gone through all the websites and have granted privilege to my «root» localhost through my terminal as well as workbench and have made all the necessary changes to my .env file as well. The error still seems to persist and I have no idea how to go forward with it now.
Any help would be much appreciated. Thank you.
Answer
Solution:
The error means Laravel is trying to connect to the database with invalid credentials.
Whenever you make change to the.env file in Laravel you need to reset the cache. You need to run this command:
php artisan config:cache
Undefined answered
Link to answer
People are also looking for solutions to the problem: your lock file does not contain a compatible set of packages. please run composer update.
Source
Share
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
I make php artisan make:auth and tried to register as a new user then I get the error. I am using Xampp for MySQL and make a database name ‘pari’ and set user: root and password: root. After starting xampp apache and SQL server and PHP artisan serve on cmd I get the same error every time.
Step 1: I have changed .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=pari
DB_USERNAME=root
DB_PASSWORD=root
and restart using php artisan serve , but again it gave that error.
Step 2: I have changed config\database.php to-
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'pari'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'root'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
but it again gave that same error.
Step 3: I tried
php artisan cache:clear
php artisan config:clear
but again get same error.
Step 4: After removing password from phpmyadmin and .env and database.php I get new error-
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pari.users' doesn't exist (SQL: select count(*) as aggregate from `users` where `email` = avinashjk1620@gmail.com)
How can i fixed this error Please help me.
I make php artisan make:auth and tried to register as a new user then I get the error. I am using Xampp for MySQL and make a database name ‘pari’ and set user: root and password: root. After starting xampp apache and SQL server and PHP artisan serve on cmd I get the same error every time.
Step 1: I have changed .env file
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=pari DB_USERNAME=root DB_PASSWORD=root
and restart using php artisan serve , but again it gave that error.
Step 2: I have changed configdatabase.php to-
'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'pari'), 'username' => env('DB_USERNAME', 'root'), 'password' => env('DB_PASSWORD', 'root'), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],
but it again gave that same error.
Step 3: I tried
php artisan cache:clear php artisan config:clear
but again get same error.
Step 4: After removing password from phpmyadmin and .env and database.php I get new error-
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pari.users' doesn't exist (SQL: select count(*) as aggregate from `users` where `email` = avinashjk1620@gmail.com)
How can i fixed this error Please help me.
Hello,
The exports use a new database driver because there was an issue running exports in Joomla 4. If you change the 127.0.0.1 to localhost in your database configuration, does the export run then?
Under the database type, do you see the PDO option there?
Hi,
changing from 127.0.0.1 to Localhost the problem persists.
my provider allows me to connect to the Mysql database only with user «localhost»
this is my config in «PHP Information» section of my Joomla 3.10:
=============
PDO
=============
PDO support: enabled
PDO drivers: mysql, odbc, pgsql, sqlite
=============
pdo_mysql
=============
PDO Driver for MySQL: enabled
Client API version: mysqlnd 7.4.28
=============
pdo_mysql.default_socket
=============
Local Value: xxxxxx
Master Value: xxxxxx
=============
PDO_ODBC
=============
PDO Driver for ODBC (unixODBC): enabled
ODBC Connection Pooling: Enabled, strict matching
=============
pdo_pgsql
=============
PDO Driver for PostgreSQL: enabled
PostgreSQL(libpq) Version: 9.2.24
=============
pdo_sqlite
=============
PDO Driver for SQLite 3.x: enabled
SQLite Library: 3.7.17
=============
mysqlnd
mysqlnd enabled
Version mysqlnd 7.4.28
Compression supported
core SSL supported
extended SSL supported
Command buffer size 4096
Read buffer size 32768
Read timeout 86400
Collecting statistics Yes
Collecting memory statistics No
Tracing n/a
Loaded plugins mysqlnd, debug_trace, auth_plugin_mysql_native_password, auth_plugin_mysql_clear_password, auth_plugin_caching_sha2_password, auth_plugin_sha256_password
API Extensions mysqli, pdo_mysql
is there a solution to fix the problem?
Many thanks.
For simplicity, let’s say this:
Computer A = Holds the MySQL DB. IPv4= 192.168.11.1
Computer B= Has an Eclipse program that wants to connect to Computer A and do stuff to the schemas. Ipv4= 192.168.22.2
Do the Following on Computer A:
It looks like you’re trying to make a new user by the name of ‘username’@’192.168.22.2’ but a different user by the name of ‘username’@’localhost’ is getting in the way/taking precedence.
Do this command to see the users:
SELECT user,host FROM mysql.user;
You should see two entries:
1) user= username, host= localhost
2) user= username, host=192.168.22.2
So do these commands:
DROP User 'username'@'localhost';
DROP User 'username'@'192.168.22.2';
Note, if you see ‘username’@’%’ user, also drop/delete that row.
Restart MySQL Workbench
Then do your original commands again:
CREATE USER 'username'@'192.168.22.2' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON databasename.* TO 'username'@'192.168.22.2';
I don’t understand why u used «***» as your password so I replaced it with ‘password’.
Then go to Computer B and open your Command Prompt/Terminal. Type in the following and you should be connected to Computer A. If you can’t connect, check Computer A’s firewall’s inbound rules and check if the MySQL Service is running on Computer A.
mysql --host=192.168.11.1 --user=username --password=password
(Make sure you have mysql setup as an environmental variable otherwise Command Prompt won’t understand the «mysql» command)
Helpful Troubleshooting Methods:
Turn off all Firewall Rules on Computer A. From Computer B’s Command Prompt/Terminal, do «ping 192.168.11.1» or «telnet 192.168.11.1 3306».
I am getting in phpMyAdmin the famous #1045 error: Access denied for user ‘root’@’localhost’ (using password: YES).
This is my /etc/phpmyadmin/config.inc.php:
/**
* Server(s) configuration
*/
$i = 0;
// The $cfg['Servers'] array starts with $cfg['Servers'][1]. Do not use $cfg['Servers'][0].
// You can disable a server config entry by setting host to ''.
$i++;
/* Authentication type */
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
//$cfg['Servers'][$i]['host'] = 'localhost';
//$cfg['Servers'][$i]['connect_type'] = 'tcp';
//$cfg['Servers'][$i]['compress'] = false;
/* Select mysqli if your server has it */
//$cfg['Servers'][$i]['extension'] = 'mysql';
/* Optional: User for advanced features */
// $cfg['Servers'][$i]['controluser'] = 'pma';
// $cfg['Servers'][$i]['controlpass'] = 'pmapass';
/* Optional: Advanced phpMyAdmin features */
// $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
// $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
// $cfg['Servers'][$i]['relation'] = 'pma_relation';
// $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
// $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
// $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
// $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
// $cfg['Servers'][$i]['history'] = 'pma_history';
// $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
/*
* End of servers configuration
*/
/*
* Directories for saving/loading files from server
*/
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
Any idea?
peterh
4,91413 gold badges29 silver badges44 bronze badges
asked Jul 19, 2010 at 11:28
1
You realize all the configuration lines are commented out? You need to uncomment and fill-in those fields for anything to happen. I think including this one would be sufficient (assuming you want it to prompt you for a username/password):
$cfg['Servers'][$i]['auth_type'] = 'cookie';
answered Jul 19, 2010 at 19:48
execute following command
$ mysqladmin -u root password abcd
and use the password in config file as ‘abcd’
or replace your password with ‘abcd’
answered Nov 18, 2010 at 12:35
Uncomment the below lines and fill the correct info:
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['host'] = 'localhost';
/* Optional: User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = ''; /*You can leave it blank, PHPmyadmin will ask you the user name and password */
answered Nov 18, 2010 at 13:37
Ramesh KumarRamesh Kumar
1,6905 gold badges18 silver badges29 bronze badges
I installed Magento 2.4.3 in ubuntu,
but when I run the below command it gave me errors like,
Command:
but when I login into PHPMyAdmin using the same id password of the database
it was worked but did not work in the terminal when I run the command.
please help me with this.
Viral Patel
1,2611 gold badge7 silver badges15 bronze badges
asked Oct 11, 2021 at 11:36
1
Try the host as 127.0.0.1 and not localhost as technically they are different
answered Oct 11, 2021 at 14:59
Goose84Goose84
2,4392 gold badges25 silver badges55 bronze badges
If the database is created and the issue still persists then try the command like this i.e. without the quotes «.
bin/magento setup:install --base-url=http://127.0.0.1/magento2/ \
--db-host=localhost
--db-name=magento
--db-user=magento
--db-password=magento \
--admin-firstname=Magento
--admin-lastname=User
--admin-email=user@example.com \
--admin-user=admin
--admin-password=admin123
--language=en_US \
--currency=USD
--timezone=America/Chicago
--use-rewrites=1 \
--search-engine=elasticsearch7
--elasticsearch-host=es-host.example.com \
--elasticsearch-port=9200
answered Oct 14, 2021 at 6:14
- Log in to the MariaDB/MySQL shell using the mysql command below.
mysql -u root -p
Now create a new database for Magento installation. Create the database ‘magentodbatabase’ and the user ‘magentodatabaseuser’ with the password ‘magentodbpassword’.
Run the MySQL queries below.
create database magentodbatabase;
Now type ‘exit’ to log out from the MySQL shell.
answered Oct 14, 2021 at 6:32
I have a server in my room on my LAN. I just rebooted my server and now when I try to connect to mysql I get the following error message
mysql -u root -p -h localhost
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I haven’t changed any settings to my knowledge and was able to log in and out until I rebooted my computer. Any advice? I know this same error message has been reported on stackoverflow and serverfault, but in the Q/A’s I read they aren’t connecting to localhost.
asked Jan 25, 2012 at 0:12
user784637user784637
1,4827 gold badges35 silver badges49 bronze badges
The procedure is about the same; restart MySQL in safe mode log in with root and no password and perform a password reset. From there do a data integrity check.
answered Jan 25, 2012 at 0:25
Tim BrighamTim Brigham
15.4k7 gold badges72 silver badges113 bronze badges
0
Here is the list of steps I followed to solve this problem (from http://24x7servermanagement.com/blog/?p=44)
#service mysqld stop or
#killall mysqld
#/usr/bin/mysqld_safe –skip-grant-tables&
#/usr/bin/mysql
mysql>use mysql;
Change the MySQL admin(root) Password using following command
mysql>update user set password=password(‘wsarxaffa’) where user=’root’ and host=’localhost’;
Flush the privileges so everything will take (It removes any privileges set by the server)
mysql>flush privileges;
mysql>quit
/etc/init.d/mysqld stop
/etc/init.d/mysqld start
mysql -u root -p
answered Jan 25, 2012 at 0:39
user784637user784637
1,4827 gold badges35 silver badges49 bronze badges
I faced this problem as well on ubuntu. In my case, the reason was that the /tmp folder was not accessible and install process was silently failing in root user creation. I’d uninstall mysql, give /tmp the right permissions and then reinstall mysql.
Please refer http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=545741
answered Apr 6, 2012 at 8:20
krishnakumarpkrishnakumarp
1,1412 gold badges7 silver badges6 bronze badges
I’ve seen this happen when mysql has been upgraded, and the grant tables were updated.
I would run /usr/bin/mysql_upgrade (or wherever the path is on your system) to fix that.
mysqld needs to be running.
answered Jan 25, 2012 at 0:26
malcolmpdxmalcolmpdx
2,2501 gold badge15 silver badges12 bronze badges
After 3 days trying i realized that there is an extension on mysql website for Win(x64). It worked for me. Exclude all from the bin folder of the original installer and copy the files from the extension.
answered Oct 2, 2016 at 18:54
При попытке выполнить вход phpMyAdmin или авторизоваться в MySQL вы можете столкнуться с ошибкой HY000/1045:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES) mysqli::real_connect(): (HY000/1045): Access denied for user 'superuser'@'localhost' (using password: NO)
Ошибка возникает, когда используемая комбинация имени пользователя, хоста и пароля не позволяет подключаться к серверу. Например, если пытаться выполнить вход под пользователем, который не существует вовсе, то возникнет именно эта ошибка.
Давайте посмотрим на следующий код, который вызывает эту ошибку:
<?php define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "databasename"); $db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
Увидели подвох? Устанавливается значение константы DB_USER, а используется для подключения DB_USERNAME, аналогично с DB_HOST и DB_SERVER. То есть в СУБД передаются неверные или пустые данные с которыми невозможно выполнить подключение.
Посмотрите на следующий код, который также вызовет ошибку:
$servername = '127.0.0.1'; $username = 'user_bob'; $password = "sdfasdf$B"; $conn = mysqli_connect($servername, $username, $password, 'any_database');
В пароле содержится специальный символ $. В принципе, в пароле можно (и даже нужно) использовать специальные символы, но некоторые из них имеют специальное значение для языков программирования или для оболочки (если подключение выполняется в командной строке). Одинарная и двойная кавычки хотя и используются одинаково для обозначения строк чтобы символы в них перестали трактоваться как другие элементы языка, но они не являются идентичными. Одинарная кавычка делает так, что любые символы теряют своё специальное значение. А в строке, помещённой в двойные кавычки, некоторые специальные символы сохраняют своё значение. То есть «sdfasdf$B» интерпретатором PHP расценивается как буквальная строка «sdfasdf» за которой следует переменная $B.
Правильно так:
$servername = '127.0.0.1'; $username = 'user_bob'; //НЕ ИСПОЛЬЗУЙТЕ ДВОЙНЫЕ КАВЫЧКИ для строк со специальными символами //$password = "sdfasdf$B"; $password = 'sdfasdf$B'; $conn = mysqli_connect($servername, $username, $password, 'any_database');
Чтобы убедиться, что проблема в пароле содержащим специальные символы, вы можете временно установить пароль на не содержащий специальных символов примерно следующей командой:
GRANT ALL PRIVILEGES ON БАЗА_ДАННЫХ.* TO 'ПОЛЬЗОВАТЕЛЬ'@'%' IDENTIFIED BY '12345';
В этом примере пароль установлен на «12345».
grep 'temporary password' /var/log/mysqld.log
Sort date (newest date)
You may see something like this;
[root@SERVER ~]# grep 'temporary password' /var/log/mysqld.log
2016-01-16T18:07:29.688164Z 1 [Note] A temporary password is generated for root@localhost: O,k5.marHfFu
2016-01-22T13:14:17.974391Z 1 [Note] A temporary password is generated for root@localhost: b5nvIu!jh6ql
2016-01-22T15:35:48.496812Z 1 [Note] A temporary password is generated for root@localhost: (B*=T!uWJ7ws
2016-01-22T15:52:21.088610Z 1 [Note] A temporary password is generated for root@localhost: %tJXK7sytMJV
2016-01-22T16:24:41.384205Z 1 [Note] A temporary password is generated for root@localhost: lslQDvgwr3/S
2016-01-22T22:11:24.772275Z 1 [Note] A temporary password is generated for root@localhost: S4u+J,Rce_0t
[root@SERVER ~]# mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root:
The existing password for the user account root has expired. Please set a new password.
New password:
Re-enter new password:
If you see it says
... Failed! Error: Your password does not satisfy the current policy requirements
That means your password needs to have a character such as ! . # - etc...
mix characters well, upper case, lower case, ! . , # etc...
New password:
Re-enter new password:
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.
Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : Y
New password:
Re-enter new password:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y
Success.
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y
Success.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
Success.
All done!
[root@SERVER ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.10 MySQL Community Server (GPL)
Watch the last 10 minutes of this video, it teaches you how you do it.
- Access to a command line or terminal
- MySQL or MariaDB installed
- User with sudo or root privileges
Step 1 – Login as Root user MySQL
mysql -u root -p
You can enable access for root using one MySQL command.
sudo mysql
Enter your password at the prompt. A MySQL shell loads.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'insert_password';
mysql> FLUSH PRIVILEGES;
Step 2 – Restart Apache Server
sudo service apache2 restart
http://[SERVER_PUBLIC_IP]/phpmyadmin
Then you will look like on your browser:
Conclusion
Recommended Linux/Ubuntu Tutorials
Alexandr1234
- Сообщения: 8
- Зарегистрирован: 2015.04.21, 17:29
Ошибка [1045] при подключении к БД в Yii2
Добрый день! Помогите пожалуйста новичку в Yii2. При попытке подключения к БД появляется ошибка:
Database Exception – yii\db\Exception
SQLSTATE[HY000] [1045] Access denied for user ‘rootadmin’@’localhost’ (using password: YES)
↵
Caused by: PDOException
SQLSTATE[HY000] [1045] Access denied for user ‘rootadmin’@’localhost’ (using password: YES)
in D:\XXAMP\htdocs\Yii2Project\vendor\yiisoft\yii2\db\Connection.php at line 579
Пользователь rootadmin существует, могу зайти под его именем и паролем в PhpMyadmin. Могу подключиться к БД из простого РНР скрипта. Могу работать с БД из этого же скрипта.
Подключение через Yii2 не получается… Весь код подключения к БД в Yii2 копировал из оф. документации: https://github.com/yiisoft/yii2/blob/ma … %8B%D1%85-
Помогите пожалуйста.
Последний раз редактировалось Alexandr1234 2015.04.21, 22:47, всего редактировалось 1 раз.
Alexandr1234
- Сообщения: 8
- Зарегистрирован: 2015.04.21, 17:29
Re: Ошибка [1045] при подключении к БД в Yii2
Сообщение
Alexandr1234 » 2015.04.21, 21:58
Нет. Yii2 basic. Вот файл db.php из папки config.
<?php
return [
‘class’ => ‘yii\db\Connection’,
‘dsn’ => ‘mysql:host=localhost;dbname=yii2basic’,
‘username’ => ‘rootadmin’,
‘password’ => ‘xxxxxxxxxx’,
‘charset’ => ‘utf8’,
];
Не занаю, этот ли config вы имели в иду, т.к. я еще «деревянный» Web программист…
Последний раз редактировалось Alexandr1234 2015.04.21, 22:50, всего редактировалось 1 раз.
padlyuck
- Сообщения: 302
- Зарегистрирован: 2015.02.03, 09:50
Re: Ошибка [1045] при подслючении к БД в Yii2
Сообщение
padlyuck » 2015.04.21, 22:31
какие права выданы пользователю в бд? была ситуация когда пользователю давался доступ с localhost, а сайт коннектился с 127,0,0,1 и мускуль не сопоставлял адрес к имени.
З.Ы. поправьте название темы. подСлючение вряд ли в поиске кто-то искать будет
padlyuck
- Сообщения: 302
- Зарегистрирован: 2015.02.03, 09:50
Re: Ошибка [1045] при подключении к БД в Yii2
Сообщение
padlyuck » 2015.04.22, 00:35
Alexandr1234 писал(а):Права у пользователя все. Пробовал менять ‘mysql:host=localhost; на ‘mysql:host=127,0,0,1 — но это не помогло.
все права — это дефолтный рут. если у вас не рут — покажите скрин прав пользователя. запятые на точки вы поменяли когда в конфиг вставляли строку 127,0,0,1 ? на какой хост распространяются права вашего пользователя
Alexandr1234
- Сообщения: 8
- Зарегистрирован: 2015.04.21, 17:29
Re: Ошибка [1045] при подключении к БД в Yii2
Сообщение
Alexandr1234 » 2015.04.23, 16:11
Вот конфиг пользователя:
— Зашел в PhpMyadmin под «rootadmin». Под ним же создавал базу «yii2basic» и таблицы в базе, вставлял данные в базу (все это в PhpMyadmin). Поэтому вроде как бы не должен быть заблочен на доступ к базе….
Пароль и имя пользователя записал в отдельный текстовый файл, копировал при помощи клавиш «Shift» + «->» посимвольно — ошибки в имени и пароле быть не должно…
Вот права пользователя:
Последний раз редактировалось Alexandr1234 2015.04.23, 16:52, всего редактировалось 1 раз.
Alexandr1234
- Сообщения: 8
- Зарегистрирован: 2015.04.21, 17:29
Re: Ошибка [1045] при подключении к БД в Yii2
Сообщение
Alexandr1234 » 2015.04.24, 15:15
Спасибо вам большое! Разобрался. Просто у меня на компе раньше был отдельно установлен MySQL, а позже я поставил сборку ХАММР. Вот я для ХАММР-а и изменил порт подключения к БД, чтобы можно было и со старым MySQL работать и со ХАММР.
Подскажите еще пожалуйста, где и как в Yii2 прописать порт для подключения к БД?
This “access denied” error is one of the most common errors you’ll get when working with MySQL.
Learn how to fix it, and see a range of solutions if the suggested fix does not work, in this article.
When you try to connect to a MySQL database on your own computer (called “localhost”), you may get this error:
Access denied for user 'root'@'localhost' (using password: YES)
You might get an error code in front of it:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
You might also get the error with “using password no”:
Access denied for user 'root'@'localhost' (using password: NO)
You’ll see this if you log into MySQL using the command line:
mysql -u root -p
What does this mean? How can you fix it?
There are a few solutions to this, which I’ve detailed below. Try one, and if it doesn’t work, try another one.
Also a tip for logging in: don’t enter your password in the command line itself, because this will be stored in your command history. Use the -p option, as mentioned above, and then you’ll be prompted to enter the password.
Solution 1: Sudo then Change Password
If you get the “access denied” error, one way to solve it is by using sudo to log in to mysql and change the root password.
Step 1: Open the command line on your system.
Step 2: Open mysql using the sudo command:
sudo mysql
Step 3: Enter the password for this account.
Step 4: Change the auth_plugin to mysql_native_password, and the password for the root account, in a single command:
ALTER USER 'root'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'your_new_password';
Substitute the word your_new_password with a new secure password that you want to use for the root account.
The mysql_native_password method is a traditional method of authentication and will allow you to login.
Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:
FLUSH PRIVILEGES;
SELECT user, plugin
FROM mysql.user
Step 7: Exit the console by pressing CTRL + D or typing exit.
exit;
Step 8: Log in to mysql using the root account and the new password you set, which should work:
mysql -u root -p
You should now be logged in to the root account in mysql.
If the above solution did not work, you may need to edit the mysql.cnf file to allow for changes to the root account.
Step 1: Open the my.cnf file. This may be stored in:
/etc/my.cnf /etc/mysql/my.cnf
If you’re not sure where it is, search your MySQL installation folder (e.g. on Windows or Mac) for the file.
If you don’t have a my.cnf file (MacOS does not include one by default). You can create one in the /etc folder if you like.
[mysqld] skip-grant-tables
Step 3: Restart the MySQL server.
Step 4: Login to the root account:
mysql -u root -p
Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:
FLUSH PRIVILEGES;
Step 6: Set a new password for the account:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_password';
Substitute the word your_new_password with a new secure password that you want to use for the root account.
Step 7: Open the my.cnf file you opened in step 1, and remove the line about skip-grant-tables, and save the file.
Step 8: Restart the MySQL server again.
Step 9: Log in to the root account again:
mysql -u root -p
You should now be able to log in successfully with your new password and not get an error.
Conclusion
If you have any questions, feel free to use the comments section below.
Introduction
If you’ve forgotten your MySQL root password, please see this article:
Understanding MySQL Users and Hosts
+------------------+-------------+
| User | Host |
+------------------+-------------+
| test-user1 | localhost |
| test-user3 | 10.0.53.185 |
| test-user2 | % |
Let’s have a look at a few scenarios where your correct password may be rejected depending on the host value:
- User
test-user1@locahost
- ✅ Can log in from the
localhost
, that is, the machine on which the MySQL service is running. - ✅ Can log in from phpMyAdmin if installed on the same localhost.
- ❌Cannot log in remotely and will get “Access denied for user (using password: YES)”.
- ✅ Can log in from the
- User
test-user2@10.0.53.185
- ✅ Can log in only from the IP address
10.0.53.185
. - ❌ Cannot log in from any other IP address “Access denied for user (using password: YES)”.
- ❌ Cannot log in from localhost “Access denied for user (using password: YES)”.
- ❌ Cannot log in from phpMyAdmin “Access denied for user (using password: YES)”.
- ✅ Can log in only from the IP address
- User
test-user3@%
- ✅ Can log in from anywhere (
%
is a wildcard).
- ✅ Can log in from anywhere (
Changing a MySQL User’s Host Value
Via Command Line
To log into a local MySQL database:
To log into a remote MySQL database, simply replace hostname_or_ip with your own.
mysql -u root -h hostname_or_ip -p
SELECT User,Host FROM mysql.user;
+------------------+-------------+
| User | Host |
+------------------+-------------+
| test-user1 | localhost |
| test-user3 | 10.0.53.185 |
| test-user2 | % |
+------------------+-------------+
3 rows in set (0.00 sec)
RENAME USER 'test-user1'@'localhost' TO 'test-user1'@'%';
You must flush MySQL privileges for changes to take affect.
Now try logging in again remotely.
Via phpMyAdmin
- Once logged into phpMyadmin, click the
mysql
database in the left-hand column. - Click the SQL tab.
- Type or paste into the SQL query box:
SELECT User,Host FROM mysql.user;
to list all MySQL users in the database. - Click Go to run the query.
- Double-click the host field beside the user your wish to change (in red below).
- Type
%
to allow anyone to log into this user from anywhere. You could also change this to a remote IP for better security. - Press
ENTER
on your keyboard to save changes.
You’re not done yet. You must now flush MySQL privileges.
- Click the SQL tab again
- Type or paste into the SQL query box:
FLUSH PRIVILEGES;
- Click Go to run the query.
You should now be able to log in remotely.
p.s. I increased my AdSense revenue by 200% using AI 🤖. Read my Ezoic review to find out how.
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
So here I am writing all the possible solutions that I have tried to resolve this error.
- How To Solve SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO) Error?
- SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO)
Solution 1: Run artisan command
First of all, Run this route-cache command.
php artisan route:cache
Then, Run this route-clear command.
php artisan route:clear
Now, Run this config-cache command.
php artisan config:cache
Then, Run this config-clear command.
php artisan config:clear
Now, optimize by running this command.
php artisan optimize
Here is All Command list.
php artisan route:cache
php artisan route:clear
php artisan config:cache
php artisan config:clear
php artisan optimize
And Now, Your error must be solved. Thanks.
Solution 2: Set Database Credentials in this way
This error also occurs when You have used a Special character in your Database then You need to define all variable Always enclose them in «». Just like this.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE="your_database_name"
DB_USERNAME="put_db_user_name _here"
DB_PASSWORD="put_db_password_here_if_have_set"
If You have no Password for your Database then define DB_PASSWORD=””.
DB_PASSWORD=""
And then run all artisan commands just like this.
php artisan route:cache
php artisan route:clear
php artisan config:cache
php artisan config:clear
php artisan optimize
And Now, Your error must be solved. Thank you.
Solution 3: delete bootstrap/cache
If Your Problem is still not resolved then just open bootstrap/cache/config.php and delete config.php file in the bootstrap/cache folder.
Conclusion
It’s all About this error. I hope We Have solved Your error. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
‘SQL error 1045 sqlstate 28000’ – What this means?
Before we move on to the reasons for this error, let’s first get an idea of this error.
Website owners face this error when querying data from the SQL server.
For instance, the complete error message looks like this:
SQLSTATE[28000] [1045] Access denied for user 'user'@'localhost' (using password: YES)
This error shows that the MySQL server disallows the user to connect to it from localhost or 127.0.0.1.
‘SQL error 1045 sqlstate 28000’ – Causes & Fixes
In our experience managing servers, we’ll see the major causes of this error and how our Dedicated Support Engineers fix it.
1) Typo in username and password
This is the most common reason for the error “sql error 1045 sqlstate 28000″.
Users may type wrong username and password while connecting to the database.
Therefore, SQL server can’t identify the authenticity of the account.
Solution
In such cases, we help website owners reset the database user password.
For example, in cPanel servers, we reset the database user password from Databases > Mysql databases > Current Users.
Also, for database driven websites like WordPress, Magento, etc., we update the new database username and password in the website configuration files.
For example, in the Magento application, we update the database name, username and password in the “app/etc/local.xml” file.
In some cases, website owners get errors like this:
SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES)
This is because, the root session don’t know the password of mysql root user.
And, it can be probably a mis-typed password during the initial setup.
Here, our Hosting Engineers reset the admin/root password after starting the MySQL in safe mode.
For example, we use the below command to reset the root password in safe mode.
update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';
2) Accessing from wrong host
MySQL uses host based restrictions for user access to enhance security.
In other words, MySQL allows user access only from hosts defined in the MySQL user table.
So, any access from remote machines whose hostnames are not defined in this user table will bounce with the error “sql error 1045 sqlstate 28000”
Solution
First, our Hosting Engineers check whether the remote host is allowed in the MySQL user table.
If not, we add the hostname of the remote machine in the MySQL user table.
For instance, we use the below command to add a host in the MySQL user table.
update user set host='hostname' where user='username';
Here, hostname is the hostname of the remote machine, and username is the MySQL user.
We’ve seen cases where server owners use wildcards(%) in host field which gives universal access to this user.
But, this is not a good practice as there is a security risk that user can access the database from any hosts.
In addition to that, due to security concerns, we always disable accessing root user from remote machines.
[You don’t have to be a MySQL expert to keep your websites online. We have experienced MySQL admins available 24/7.]
3) User doesn’t exist
Similarly, this error “sql error 1045 sqlstate 28000” occurs when the user trying to access the database doesn’t exist on the MySQL server.
For example, if you access MySQL using a testuser that doesn’t exist, you can see the following error.
# mysql -u testuser -p Enter password: ERROR 1045 (28000): Access denied for user 'testuser'@'localhost' (using password: YES)
Solution
In such cases, our Support Engineers first check whether the user exists in the MySQL user table.
If not, we check the user’s requirement to access the database and if it is valid, we create a user with that username.
4) Existence of Anonymous users
Website owners face this error when there are anonymous MySQL users like ”@localhost or ”@127.0.0.1.
That is, when a client tries to connect to the database, the MySQL server looks through the rows in the user table in a sorted order.
The server uses the first row that matches the most specific username and hostname.
So, here the anonymous user (‘ ‘@localhost) precedes any other users like ‘user’@localhost when connecting from localhost.
And, use the anonymous user password to connect to the server.
Finally, the result is “sql error 1045 sqlstate 28000“.
Solution
Our Hosting Engineers check the MySQL user table and remove the anonymous user account.
For example, we use the below command to remove the anonymous user from MySQL.
delete from user where User = ' ';
5) Insufficient privileges
Likewise, insufficient privileges for the user to access the database can also result in this error.
Solution
In such cases, we assign proper access rights for the user to access the database.
For example, in cPanel servers, we manage user privileges from:
cPanel > Mysql databases > Current databases > Privileged users > Click on the database user.
[Struggling with database user permissions and privileges? Our MySQL Experts are here for your help.]
MySQL 1045 error Access Denied triggers in the following cases
1) Connecting to wrong host:
[engineer@percona]# mysql -u root -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) |
If not specifying the host to connect (with -h flag), MySQL client will try to connect to the localhost instance while you may be trying to connect to another host/port instance.
Fix: Double check if you are trying to connect to localhost, or be sure to specify host and port if it’s not localhost:
[engineer@percona]# mysql -u root -psekret -h <IP> -P 3306 |
2) User does not exist:
[engineer@percona]# mysql -u nonexistant -psekret -h localhost mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Double check if the user exists:
mysql> SELECT User FROM mysql.user WHERE User=‘nonexistant’; Empty set (0.00 sec) |
If the user does not exist, create a new user:
mysql> CREATE USER ‘nonexistant’@‘localhost’ IDENTIFIED BY ‘sekret’; Query OK, 0 rows affected (0.00 sec) |
3) User exists but client host does not have permission to connect:
[engineer@percona]# mysql -u nonexistant -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: You can check to see which host user/host MySQL allows connections with the following query:
mysql> SELECT Host, User FROM mysql.user WHERE User=‘nonexistant’; +————-+————-+ | Host | User | +————-+————-+ | 192.168.0.1 | nonexistant | +————-+————-+ 1 row in set (0.00 sec) |
If you need to check from which IP the client is connecting, you can use the following Linux commands for server IP:
[engineer@percona]# ip address | grep inet | grep -v inet6 inet 127.0.0.1/8 scope host lo inet 192.168.0.20/24 brd 192.168.0.255 scope global dynamic wlp58s0 |
or for public IP:
[engineer@percona]# dig +short myip.opendns.com @resolver1.opendns.com 177.128.214.181 |
You can then create a user with correct Host (client IP), or with ‘%’ (wildcard) to match any possible IP:
mysql> CREATE USER ‘nonexistant’@‘%’ IDENTIFIED BY ‘sekret’; Query OK, 0 rows affected (0.00 sec) |
4) Password is wrong, or the user forgot his password:
[engineer@percona]# mysql -u nonexistant -pforgotten mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Check and/or reset password:
You cannot read user passwords in plain text from MySQL as the password hash is used for authentication, but you can compare hash strings with “PASSWORD” function:
mysql> SELECT Host, User, authentication_string, PASSWORD(‘forgotten’) FROM mysql.user WHERE User=‘nonexistant’; +————-+————-+——————————————-+——————————————-+ | Host | User | authentication_string | PASSWORD(‘forgotten’) | +————-+————-+——————————————-+——————————————-+ | 192.168.0.1 | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 | | % | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 | +————-+————-+——————————————-+——————————————-+ 2 rows in set, 1 warning (0.00 sec) |
We can see that PASSWORD(‘forgotten’) hash does not match the authentication_string column, which means password string=’forgotten’ is not the correct password to log in. Also, in case the user has multiple hosts (with different password), he may be trying to connect using the password for the wrong host.
In case you need to override the password you can execute the following query:
mysql> set password for ‘nonexistant’@‘%’ = ‘hello$!world’; Empty set (0.00 sec) |
5) Special characters in the password being converted by Bash:
[engineer@percona]# mysql -u nonexistant -phello$!world mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Prevent bash from interpreting special characters by wrapping password in single quotes:
[engineer@percona]# mysql -u nonexistant -p’hello$!world’ mysql: [Warning] Using a password on the command line interface can be insecure ... mysql> |
6) SSL is required but the client is not using it:
mysql> create user ‘ssluser’@‘%’ identified by ‘sekret’; Query OK, 0 rows affected (0.00 sec) mysql> alter user ‘ssluser’@‘%’ require ssl; Query OK, 0 rows affected (0.00 sec) ... [engineer@percona]# mysql -u ssluser -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘ssluser’@‘localhost’ (using password: YES) |
Fix: Adding –ssl-mode flag (–ssl flag is deprecated but can be used too)
[engineer@percona]# mysql -u ssluser -psekret —ssl-mode=REQUIRED ... mysql> |
You can read more in-depth on how to configure SSL in MySQL in the blog post about “Setting up MySQL SSL and Secure Connections” and “SSL in 5.6 and 5.7“.
7) PAM backend not working:
mysql> CREATE USER ‘ap_user’@‘%’ IDENTIFIED WITH auth_pam; Query OK, 0 rows affected (0.00 sec) ... [engineer@percona]# mysql -u ap_user -pap_user_pass mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘ap_user’@‘localhost’ (using password: YES) |
Fix: Double check user/password is correct for the user to authenticate with the PAM currently being used.
In my example, I am using Linux shadow files for authentication. In order to check if the user exists:
[engineer@percona]# cat /etc/passwd | grep ap_user ap_user:x:1000:1000::/home/ap_user:/bin/bash |
To reset password:
[engineer@percona]# sudo passwd ap_user Changing password for user ap_user. New password: |
Finally, if you are genuinely locked out and need to circumvent the authentication mechanisms in order to regain access to the database, here are a few simple steps to do so:
- Stop the instance
- Start the instance
- Stop the instance
- Edit my.cnf and remove skip-grant-tables and skip-networking
- Start MySQL again
Learn more about Percona Server for MySQL
Создание нового пользователя при ошибке HY000/1045
Эта ошибка является вариантом рассмотренной ошибки — но разница в том, что необходимый пользователь действительно отсутствует и его нужно создать:
phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)
В данном случае это пользователь pma, но вы можете применять описанные команды для создания любых пользователей, заменяя в командах «pma» на нужное вам имя.
В терминале войдите в MySQL как root. Возможно, вы создали пароль root при первой установке MySQL или пароль может быть пустым, и в этом случае вы можете просто нажать ENTER, когда будет предложено ввести пароль.
sudo mysql -u root -p
Теперь добавьте нового пользователя MySQL с именем пользователя по вашему выбору. В этом примере мы называем его pma. Обязательно замените ЗДЕСЬ ПАРОЛЬ своим собственным. Символ % здесь указывает MySQL разрешить этому пользователю входить в систему из любого места удалённо (а не только с локального компьютера). Если вам нужна повышенная безопасность, вы можете заменить это IP-адресом.
CREATE USER 'pma'@'%' IDENTIFIED BY 'ЗДЕСЬ ПАРОЛЬ';
Теперь мы предоставим нашему новому пользователю привилегию суперпользователя.
GRANT ALL PRIVILEGES ON *.* TO 'pma'@'%' WITH GRANT OPTION;
Теперь перейдите к файлу config.inc.php (может располагаться, например, в /etc/phpmyadmin/config.inc.php) и добавьте туда следующие строки:
/* User for advanced features */ $cfg['Servers'][$i]['controluser'] = 'pma'; $cfg['Servers'][$i]['controlpass'] = 'ЗДЕСЬ ПАРОЛЬ';
Связанные статьи
- Как установить веб-сервер Apache с PHP 7, MariaDB/MySQL и phpMyAdmin (LAMP) на Ubuntu (67.9%)
- Как включить доступ root к MySQL и MariaDB с любых хостов (67.9%)
- Ошибка «ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/run/mysqld/mysqld.sock’ (2 «No such file or directory»)» (РЕШЕНО) (65.1%)
- Ошибка «Failed — Network error» во время экспорта в phpMyAdmin (РЕШЕНО) (65.1%)
- Как установить веб-сервер (Apache, PHP, MySQL, phpMyAdmin) на Linux Mint, Ubuntu и Debian (62.8%)
- Гостевая машина VirtualBox не загружается если выбран тип подключения «Сетевой мост» (РЕШЕНО) (RANDOM — 1.2%)
Answer
Make sure your database was created using utf8mb4_unicode_ci collation. This should fix your 1071 error.
Alternatively you can add Schema::defaultStringLength(191); to your boot() method in appProvidersAppServiceProvider.php.
Edit: Make sure to add use IlluminateSupportFacadesSchema;.
Форум
- Первое новое сообщение
- Поиск
ERserver
- Сообщения: 311
- Зарегистрирован: 03 авг 2015, 02:19
- Откуда: СССР
- Контактная информация:
doc777
- Сообщения: 1
- Зарегистрирован: 22 окт 2021, 20:36
Создано на основе phpBB® Forum Software © phpBB Limited
Разработчик визуального стиля Arty — MrGaby
Контакты:
, предоставляем бесплатную удалённую техническую поддержку через TeamViewer
© 2010-2021 «OSPanel.io»
User Error in connection to db Mysql
I have this error SQLSTATE[HY000] [1045] Access denied for user c1234_x@localhost
My code to connection is:
$sql_details = array(
‘user’ => ‘c1234_xyz’,
‘pass’ => ‘gatorei’,
‘db’ => ‘c1234_xyz’,
‘host’ => ‘localhost’,
);
// user and db have a same name.
This data is to server in the cloud (not local ).
Plis, any help is wellcome!
Thanks.