Skip to content
Advertisement

How can I solve the uncaught PDOException “SQLSTATE[HY000] [1045] Access denied for user…”?

I’m using a free hosting solution for my MySQL database. However, when I try to connect to it through my PHP code it throws me a uncaught PDOException error and my access is denied. I can’t seem to find why the connection is denied as my credentials are correct.

I’m using Ionic 2 framework, if that helps.

Error:

<b>Fatal error</b>:  Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'sql10181809'@'153.92.0.10' (using password: YES) in /storage/ssd5/403/2053403/public_html/escanerproducto.php:33
Stack trace:
#0 /storage/ssd5/403/2053403/public_html/escanerproducto.php(33): PDO-&gt;__construct('mysql:host=sql1...', 'sql10181809', 'xE2x81xA0xE2x81xA0xE2x81xA0dfFf6l...')
#1 {main}
  thrown in <b>/storage/ssd5/403/2053403/public_html/escanerproducto.php</b> on line <b>33</b><br />

PHP connection code:

<?php
    @$db = new PDO("mysql:host=sql10.freesqldatabase.com;dbname=sql10181809", "sql10181809", "PASS");

    if($db){
        $sql = "select * from producto WHERE
                    codigo_barra='" . $codigodebarra . "'";

        $query = $db->prepare($sql);
        $query->execute();
        $query->setFetchMode(PDO::FETCH_NUM);
        if($fila = $query->fetch()){
            $nombre = $fila[2];
            $resultados_finales = array("nombre"=>$nombre);
            echo json_encode($resultados_finales);
        }
        else{
            $resultados_finales = array("mensage"=>"error");
            echo json_encode($resultados_finales);
        }
    }
    else {
        $resultados_finales = array('mensage' => "ERROR.");
        echo json_encode($resultados_finales);
    };
?>

Advertisement

Answer

The best way to catch the exception is to put your code in a try-catch block. But in your case I think you are putting the password in incorrect. The code which causes error (exception) should be in try block and then catch it like so:

try{
   $db = new PDO("mysql:host=sql10.freesqldatabase.com;dbname=sql10181809",
                 "sql10181809", "PASS");
   $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
    echo $e->getMessage() . '  ' . '   ' . getCode() . '  ' . getLine() . '
      ' . getFile();
}

You can read more about exception handling here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement