0

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,

4
  • create a new php file and check the pdo support with phpinfo() ? Commented Dec 10, 2012 at 6:39
  • OK, thanks , let me check, does it show it in some section ? Commented Dec 10, 2012 at 6:41
  • yes it will show you the all information that you need, php version, pdo support exc. Commented Dec 10, 2012 at 6:41
  • OK i have the phpinfo() for pdo, I am adding it in the question.. Commented Dec 10, 2012 at 6:44

1 Answer 1

2

You're missing host= from your DSN string, it should be like this,

new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.