Reputation: 75
I have created a class of DB and called that class on a page but I do not know what the problem is I keep getting an unusual error, found the similar issues on Google but couldn't have solved this problem.
This is the error :
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
Here is my db class
class db {
private $host;
private $db_name;
private $db_user;
private $db_password;
public function connect() {
$db_name = $this->db_name;
$db_user = $this->db_user;
$db_pass = $this->db_password;
$db_host = $this->host;
$db_name = 'database name';
$db_user = 'username';
$db_pass = 'password';
$db_host = 'localhost:3306';
try {
$connect = new PDO('mysql:dbname=$db_name;host=$db_host;', $db_user, $db_pass);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection Successfull";
} catch(PDOException $e) {
echo "Connection Failed : " . $e->getMessage();
}
}
}
This is the code I am using to test if this is only a warning or it is a failed connection to the data base
$users = new users();
$connection = new db();
$connect = $connection->connect();
$sql = $connect->prepare("SELECT * FROM users");
$sql->execute();
while($data = $sql->fetch(PDO::FETCH_ASSOC)) {
echo $data['name'];
}
Upvotes: 0
Views: 103
Reputation: 35149
The single quotes (in ... new PDO('mysql:dbname=$db_name;host=$db_host;', ...
) don't interpolate/use the variables - with that code you are connecting to a machine called '$host
', not the value of the $host
variable.
My #1 debugging tip - print what is actually happening, not what you think must be - it's surprising how often something looks obviously right, but is clearly incorrect when properly shown what is actually being delivered to the system.
As for the $connect = $connection->connect();
line, yes - you need to return $connect;
out of the function. That variable is what allows you to access the PDO functionality - it has the information within it about actually being able to talk to the database server. (In this instance, sending the SQL that you are first prepare
-ing).
Upvotes: 2