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:
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 />";
}
normally means that there is no MySQL server running on the system or that you are using an incorrect Unix socket file name or TCP/IP port number when trying to connect to the server. You should also check that the TCP/IP port you are using has not been blocked by a firewall or port blocking service.
Check that the DB username, DB password, database host, and database port are correct. (if you are unsure, reach out to your database administrator or check in your web hosting account for the up to date credentials). If the config file references host = "localhost" , you can try to change it to 127.0.
Yes, it is possible.
It seems your server just misconfigured
use 127.0.0.1
instead of localhost
in DSN.
$dsn = 'mysql:host=127.0.0.1; dbname=practice; charset=utf8';
$pdo = new PDO($dsn, $db_user, $db_pass, $opt);
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
Just in case anyone else lands here from google. I had the exact same problem and restarting apache fixed it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With