Erro de ligação (connection error)

<?php

	$servidor = "localhost";
	$usuario = "user_****";
	$senha = "az*****I";
	$dbname = "c******2";

try {

    $pdo = new PDO('mysql:host=$servidor;dbname=$dbname;charset=utf8', $usuario, $senha);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e){
    echo "Erro: Conexão com banco de dados não foi realizada com sucesso. Erro gerado " . $e->getMessage();
}	
?>

Error generated SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: This host is not known.

The credentials are the same but it gives an error in a server window, in Linux it works quite well. how can I solve ???

You are using single-quotes around this string, so the php variables are NOT being replaced with their value. Use double-quotes.

When you make the connection, you should also set the emulated prepared query setting to false, you want to run real prepared queries whenever possible, and set the default fetch mode to assoc, so that you don’t need to specify it in each fetch statement.

There’s no good reason to catch and handle a connection error in your code. Remove the try/catch logic and let php catch and handle any connection error. The only database errors you should catch and handle in your code are for user recoverable errors, such as when inserting/updating duplicate user submitted data.

1 Like

Ok, thanks, I’ll test your option and give you feedback

Thank you, it worked perfectly, I put the double quotes and removed everything else, leaving just what is below

 $pdo = new PDO("mysql:host=$server;dbname=$dbname;charset=utf8", $user, $password);
 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Sponsor our Newsletter | Privacy Policy | Terms of Service