Question

MySQL and PHP returning HTTP error 500

I’m trying to connect to my MySQL database with php, and I’m getting a http 500 error, and the following in the error log.

[Sat Aug 11 07:33:08.899904 2018] [php7:error] [pid 18763] [client 75.97.225.218:57986] PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost' in /var/www/html/createaccount.php:14\nStack trace:\n#0 /var/www/html/createaccount.php(14): PDO->__construct('mysql:host=127....', 'root', 'password123', Array)\n#1 {main}\n  thrown in /var/www/html/createaccount.php on line 14

This is the code for createaccount.php

<?php
$host = '127.0.0.1';
$db   = 'databaseDB';
$user = 'root';
$pass = 'password123';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
?>


And I can log in with mysql -u root -p and then entering the password password123. So I know it’s the password, or at least I think so, why else would it let me log in.

Subscribe
Share

Try using localhost instead of 127.0.0.1

@Mohsen47 No I get access denied for user

Can you also connect using this command mysql -uroot -p -h127.0.0.1 databaseDB?


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi @accidentallycompiled,

The bellow steps should help you solve your problem

  • Open & Edit /etc/my.cnf or /etc/mysql/my.cnf, depending on your distro.
  • Add skip-grant-tables under [mysqld]
  • Restart Mysql
  • You should be able to login to mysql now using the below command mysql -u root -p
  • Run mysql> flush privileges;
  • Set new password by ALTER USER ‘root’@‘localhost’ IDENTIFIED BY ‘NewPassword’;
  • Go back to /etc/my.cnf and remove/comment skip-grant-tables
  • Restart Mysql

Once done, make sure root has all the needed privileges like so

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

You’ll need to be in MySQL to execute the above command

Regards, KDSys