I am trying to using the PDO module in my PHP code to connect to the database. I have read and search the similar topics, but I can't figure out what I have done wrong. Please help me to solve the issue.
-
Apache version: Apache/2.2.21 (Win32) PHP/5.3.10
-
in the php.ini file, I un-commented the line: extension=php_mysql.dll
2a. phpinfo function showed 'Loaded Configuration File' location is C:\php\php.ini
2b. PDO driver information showed by phpinfo function:
under PDO section: PDO drivers–>Mysql (enabled)
under PDO Driver for MySQL section: client API version–>mysqlnd 5.0.8-dev – 20102224 – $Revision: 321634 $ (enabled)
Code I used to connection to the database
$db_user = "uid";
$db_pass = "pd";
$db_connect = new PDO('mysql:host=locahost; dbname=practice; charset=UTF-8', $db_user, $db_pass);
if($db_connect){
print "connected to the db " . "<br />";
} else{
print "error connects to the db. " . mysql_error();
}
The error message I received:
- Warning: PDO::__construct() [pdo.–construct]: php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\server\htdocs\html-exer\handle_reg3.php on line 14
- Warning: PDO::__construct() [pdo.–construct]: [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. (trying to connect via tcp://locahost:3306) in C:\server\htdocs\html-exer\handle_reg3.php on line 14
- Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. ' in C:\server\htdocs\html-exer\handle_reg3.php:14 Stack trace: #0 C:\server\htdocs\html-exer\handle_reg3.php(14): PDO->__construct('mysql:host=loca…', 'root', 'password') #1 {main} thrown in C:\server\htdocs\html-exer\handle_reg3.php on line 14
Edit: Added answer asking for further information that will no doubt be deleted shortly:
Hello Your Common Sense:
Thanks for the code fragment. It helped me to resolve the issue. It appears that the charset may be the cause. Here is my code to connect to the db
$dsn= 'mysql:host=localhost; dbname=practice; charset=utf8';
$db_user = "root";
$db_pass = "mypd";
$db_connect = new PDO($dsn, $db_user, $db_pass);
if($db_connect){
print "connected to the db " . "<br />";
}
Best Answer
It seems your server just misconfigured
use
127.0.0.1
instead oflocalhost
in DSN.You need to read error messages.
It says your PDO have problems connecting to localhost. So, you need to change an address for PDO connect string.
Also you were using wrong charset name, I've corrected it
Also,
mysql_error()
is useless with PDO. No need to call this function, you have an error thrown already