Ошибка — SQLSTATE[HY000] [1045]
Сама ошибка ->:
Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000] [1045] Access denied for user »@’localhost’ (using password: NO)’ in D:\Server\OpenServer\domains\e-shopper.ru\app\components\db.php:8 Stack trace: #0 D:\Server\OpenServer\domains\e-shopper.ru\app\components\db.php(8): PDO->__construct(‘mysql:host=;dbn. ‘, NULL, NULL) #1 D:\Server\OpenServer\domains\e-shopper.ru\app\models\Product.php(9): Db::getConnection() #2 D:\Server\OpenServer\domains\e-shopper.ru\app\controllers\SiteController.php(11): Product::getLatestProducts(6) #3 [internal function]: SiteController->actionIndex() #4 D:\Server\OpenServer\domains\e-shopper.ru\app\components\route.php(41): call_user_func_array(Array, Array) #5 D:\Server\OpenServer\domains\e-shopper.ru\index.php(6): Router->run() #6 thrown in D:\Server\OpenServer\domains\e-shopper.ru\app\components\db.php on line 8
class Db{ public static function getConnection(){ $paramsPath = ROOT . '/app/config/db_params.php'; $params = require_once($paramsPath); $dsn = "mysql:host= ;dbname= "; $db = new PDO($dsn, $params['user'], $params['password']); $db->exec("set names utf8"); return $db; } }
return array( 'host' => 'localhost', 'dbname' => 'phpshop', 'user' => 'root', 'password' => '', );
Добавлено через 13 часов 34 минуты
проблема решена, нужно разрешить подключать файл с данными для дб несколько раз, так как на основе них создается объект PDO. Если использовать подключение — единожды, при втором использовании этих данных, объект будет пуст, что в свою очередь вызовет фатальную ошибку.
Как пофиксить ошибку «Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000] [1045] Access denied for user »@’localhost’»?
Здравствуйте, наткнулся у себя на вот такую ошибку, пароль, хост, юзер, имя бд все верно. Запрос sql так же верен(протестил в бд).
Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000] [1045] Access denied for user »@’localhost’ (using password: NO)’ in D:\Server\OpenServer\domains\e-shopper.ru\app\components\db.php:8 Stack trace: #0 D:\Server\OpenServer\domains\e-shopper.ru\app\components\db.php(8): PDO->__construct(‘mysql:host=;dbn. ‘, NULL, NULL) #1 D:\Server\OpenServer\domains\e-shopper.ru\app\models\Product.php(9): Db::getConnection() #2 D:\Server\OpenServer\domains\e-shopper.ru\app\controllers\SiteController.php(11): Product::getLatestProducts(6) #3 [internal function]: SiteController->actionIndex() #4 D:\Server\OpenServer\domains\e-shopper.ru\app\components\route.php(41): call_user_func_array(Array, Array) #5 D:\Server\OpenServer\domains\e-shopper.ru\index.php(6): Router->run() #6 thrown in D:\Server\OpenServer\domains\e-shopper.ru\app\components\db.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();
Оценить 2 комментария
Catching PHP PDO exceptions
How to handle PHP PDO exceptions with the try and catch method to control the flow of any potential errors with PDO connections and queries.
The try and catch exceptions method is a more suited way to get a grasp on problems that coincidently if not handled will throw a fatal error for an uncaught exception bringing your code to a halt.
Now to handle PDO exceptions for a connection function:
function db_connect() < $host = '127.0.0.1'; $db_name = 'database_name'; $db_user = 'root'; $db_password = 'password'; $db = "mysql:host=$host;dbname=$db_name;charset=utf8mb4"; $options = array(PDO::ATTR_ERRMODE =>PDO::ERRMODE_EXCEPTION); try < $db_con = new PDO($db, $db_user, $db_password, $options); return $db_con; >catch (PDOException $e) < echo "PDO Error: " . $e->getMessage(); > >
When calling this function to create a connection assuming the password/username is incorrect this will be outputted:
PDO Error: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
The PDO exception has been caught. If the details were correct then the connection object would be returned.
Now using this try and catch method for a PDO MySQL query:
try < $db = db_connect(); $insert = $db->prepare("INSERT INTO `table` (`col`, `col2`) VALUES (?, ?)"); $insert->execute([1, 'Gary']); > catch (PDOException $e) < echo "Insert Error: " . $e->getMessage(); >
Once again the exception will be caught and handled properly when the insert query has an error and cannot complete.