I have this code for a database connection with PDO, and it gives me the following error: ERROR: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
Here is the code:
<?php
class Conexion{
private static $conexion;
public static function abrir_conexion(){
if(!isset(self::$conexion)){
try{
include_once "config.inc.php";
/*
$dsn="mysql:host={$this->nombre_servidor};dbname=$this->nombre_base_datos;charset=UTF8";
$mOptions=array(
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
)
self::$conexion=new PDO($dsn, $username, $password, $mOptions);
*/
self::$conexion = new PDO("mysql:host=$nombre_servidor; dbname=$nombre_base_datos", $nombre_usuario, $password);
self::$conexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$conexion -> exec("SET CHARACTER utf8");
print "abierta";
}catch(PDOException $ex){
print "ERROR: " . $ex -> getMessage() . "<br>";
die();
}
}
}
public static function cerrar_conexion(){
if (isset(self::$conexion)){
self::$conexion = null;
print "cerrada";
}
}
// Para usar referencia a conexion fuera de esta clase ya que es privada
public static function obtener_conexion(){
return self::$conexion;
}
}
?>
config.inc.php:
<?php
// $config= array("nombre_servidor" => "localhost","nombre_usuario" => "root","password" => "","nombre_base_datos" => "blog");
$nombre_servidor = "localhost";
$nombre_usuario = "root";
$password = "";
$nombre_base_datos = "blog";
?>
What I have commented in the middle of the code is another test I have done using this link( Error: SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO) ) but it still doesn't work for me, and I don't know how to use mysqli.
Here the database users: [ ]
Once the DSN has been corrected, adding the port, necessary in some cases, it should be said that you must put the charset if you want
utf8
, otherwise you could have problems with accented values, but it is better to put it in DSN.On the other hand, it is not convenient to bother the connection once it has been created, neither to configure the charset through an SQL query (which was the second error in your case because that query was wrong), nor to set the options, since PDO admits a fourth parameter for it, which you can pass as an array to the constructor.
Also, turning off emulated setups is a security issue, you shouldn't ignore it.
In fact, you gave up those good practices, as you can see in the commented block of your code...
Another thing, it is safer to use the IP as the port, than to use the name.
Therefore, your code can be written like this: