简体   繁体   中英

Php database connection failure using PDO

I get an error when I use this code to list rows of a table

// Specify your table name
$table_name = 'table_stats';
$hostname = '172.16.11.2';
$username = 'user_stats';
$password = 'stats';
$dbname = 'db_stats';


$dbh  = new PDO("mysql:$hostname;dbname=$dbname",$username,$password);
$stmt = $dbh->query("SELECT * FROM $table_name", PDO::FETCH_ASSOC);
foreach($stmt as $row) { // PDOStatement implement Traversable interface, so you can just loop over the resultset. Sweet!
    print_r($row);
}

?>

and I get this error

 Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)' in /home/mahmedne/public_html/android/updates/test.php:12 Stack trace: #0 /home/mahmedne/public_html/android/updates/test.php(12): PDO->__construct('mysql:172.16.25...', 'mahmedne_stats', 'stats') #1 {main} thrown in /home/mahmedne/public_html/android/updates/test.php on line 12

I can confirm that database settings are 100% correct , using same values if I connect like

     if (!mysql_connect($db_host, $db_user, $db_pwd))
         die("Can't connect to database");

Then it works but not with I do new PDO()

Please advise, is it possible that my is providing limited functionality of PHP ? I am checking this code on web host and not on my local machine

here is th PDO related info that i got using phpinfo()

PDO

PDO support enabled
PDO drivers sqlite, sqlite2, mysql

pdo_mysql

PDO Driver for MySQL    enabled
Client API version  5.1.65

Directive   Local Value Master Value
pdo_mysql.default_socket    /var/lib/mysql/mysql.sock   /var/lib/mysql/mysql.sock

pdo_sqlite

PDO Driver for SQLite 3.x   enabled
SQLite Library  3.7.7.1

Thanks,

您从DSN字符串中丢失了host= ,它应该是这样的,

new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM