开发者

PHP - Variables not replaced in PDO connection string

Strange issue - I have a live copy of a database class (using PDO) that works fine. I have a copy on my machine using WAMPServer which does not.

The connection string is as follows (a snippet from the class):

$host = 'localhost';
$user = 'user';
$pass = 'password';
$dbname = 'my_dbname';

self::$_instance = new PDO('mysql:host=$host;dbname=$dbname', $user, $pass);

The error messages I get are:

Warning: PDO::__construct() [pdo.--construct]: php_network_getaddresses: ge开发者_如何学Gotaddrinfo failed: No such host is known. in <path> on line 41

Warning: PDO::__construct() [pdo.--construct]: [2002] php_network_getaddresses: getaddrinfo failed: No such host is kn (trying to connect via tcp://$host:3306) in <path> on line 41

I have no idea why it's not working locally whereas online its fine. If I change the line itself to the below it works fine:

self::$_instance = new PDO('mysql:host=localhost;dbname=my_dbname', $user, $pass);

Thanks :)


Use double quotes new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); otherwise the variables will not inserted into the string. Another way could be

new PDO(sprintf('mysql:host=%s;dbname=%s', $host, $dbname), $user, $pass);


self::$_instance = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

You need to use double quotes.


Variables are not parsed with single quotes. you have to enclose them with double quotes.

 self::$_instance = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);


Both answer above don't work by me. I use:

new PDO("mysql:host=".$host.";dbname=".$dbname, $user, $pass);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜