Why is this PHP-PDO script failing to connect to MySQL server on localhost? -
ubuntu 14.04, mysql 5.5, php5, php5-mysql - nothing outside ubuntu 14.04 distro versions - here's error , code:
sqlstate[hy000] [2005] unknown mysql server host '(localhost)' (11)
<?php $db_host='localhost'; $db_name='my_guitar_shop2'; $db_user='included'; $db_pass='included'; try { $conn = new pdo("mysql:host=($db_host);dbname=($db_name)", $db_user, $db_pass); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $query = $conn->query('select * products'); while($row = $query->fetch(pdo::fetch_obj)) { $results[] = $row; } print r($results); } catch(pdoexception $e) { echo 'error : ' . $e->getmessage(); } ?>
a mysqli version of code (not shown) - returns data mysql database. php-pdo version of code returns error. have substituted loop address, , pc's ip, , various combinations. far mysqli works. want able use pdo. there error in script? wrong?
this app limited comments 180 characters, , don't know how respond more code, i'm editing question. sorry ignorance.
this ended worked:
<?php define("sqlhost", "localhost"); define("sqluser", "included"); define("sqlpass", "included"); define("sqlsgbd", "my_guitar_shop2"); $pdo = new pdo('mysql:host=' . sqlhost . ';dbname=' . sqlsgbd . ';charset=utf8', sqluser, sqlpass); if ($pdo) { $stmt = $pdo->prepare("select productname, description, listprice products"); if ($stmt) { if($stmt->execute()); { while( $row = $stmt->fetch()) { echo "item: " . $row['productname']."<br/>"; echo "description: " . $row['description']."<br/>"; echo "list price: " . $row['listprice']."<br/>"; echo "<p> </p>"; } } } } ?>
i interested in getting pdo work, stripped out error checking. again responses.
look closely @ error message:
sqlstate[hy000] [2005] unknown mysql server host '(localhost)'
you see hostname in parentheses. looking @ code reason obvious
$conn = new pdo("mysql:host=($db_host);dbname=($db_name)", $db_user, $db_pass);
there parentheses, too. remove them!
$conn = new pdo("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);