1

I am trying to connect to MySQL database with pdo but keep getting this error:

Warning: Use of undefined constant username - assumed 'username' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\first\index.php on line 2

Warning: Use of undefined constant password - assumed 'password' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\first\index.php on line 2

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' (using password: YES) in C:\xampp\htdocs\first\index.php:2 Stack trace: #0 C:\xampp\htdocs\first\index.php(2): PDO->__construct('mysql:host=loca...', 'username', 'password') #1 {main} thrown in C:\xampp\htdocs\first\index.php on line 2

here's my code:

<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=dbname', username, password);
 ?>
user17289472
  • 41
  • 1
  • 2
  • you did not define the constants username and password, or you meant to type $username and $password. (or you forgot the quotes: "username" when that actually your username to be used...) – Ivo P Dec 15 '21 at 00:31
  • and always start reading the first error or warning message. Once that is solved 9 out of 10 times the other errors are gone as well – Ivo P Dec 15 '21 at 00:32
  • https://stackoverflow.com/questions/31154124/sqlstatehy000-1045-access-denied-for-user-usernamelocalhost-using-cakep seems to have good answer – revengeance Dec 23 '21 at 17:02
  • possible duplicate of https://stackoverflow.com/questions/31154124/sqlstatehy000-1045-access-denied-for-user-usernamelocalhost-using-cakep – revengeance Dec 23 '21 at 17:02

1 Answers1

0

It's because the username and password are not variables. They are missing the $

<?php

$username = 'myUsername';
$password = 'myPassword';

$pdo = new PDO('mysql:host=localhost;port=3306;dbname=dbname', $username, $password);
 ?>
joeb
  • 777
  • 8
  • 28
  • I tries: now I get this error: Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'myUsername'@'localhost' (using password: YES) in C:\xampp\htdocs\first\index.php:8 Stack trace: #0 C:\xampp\htdocs\first\index.php(8): PDO->__construct('mysql:host=loca...', 'myUsername', 'myPassword') #1 {main} thrown in C:\xampp\htdocs\first\index.php on line 8 – user17289472 Dec 15 '21 at 02:50
  • yes, that is because you did not replace `myUsername` with the username that you are using. You need to replace `myUsername` and `myPassword` with the correct credentials – joeb Dec 15 '21 at 12:33
  • I don't know what you mean by correct credentials, is this my computer username and password? – user17289472 Dec 18 '21 at 01:13
  • you need to add the credentials that you created for the user you created for the mysql database you're trying to access. – joeb Dec 18 '21 at 02:20