PHP - PDO 连接字符串中未替换的变量
奇怪的问题 - 我有一个数据库类的实时副本(使用 PDO),工作正常。我的机器上有一个使用 WAMPServer 的副本,但没有。
连接字符串如下(来自类的片段):
$host = 'localhost';
$user = 'user';
$pass = 'password';
$dbname = 'my_dbname';
self::$_instance = new PDO('mysql:host=$host;dbname=$dbname', $user, $pass);
我收到的错误消息是:
Warning: PDO::__construct() [pdo.--construct]: php_network_getaddresses: getaddrinfo 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
我不知道为什么它不能在本地工作,而在线则可以。如果我将行本身更改为下面的内容,它就可以正常工作:
self::$_instance = new PDO('mysql:host=localhost;dbname=my_dbname', $user, $pass);
谢谢:)
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: getaddrinfo 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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用双引号
new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
否则变量将不会插入到字符串中。另一种方式可能是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您需要使用双引号。
You need to use double quotes.
变量不使用单引号进行解析。你必须用双引号将它们引起来。
Variables are not parsed with single quotes. you have to enclose them with double quotes.
上面的两个答案对我来说都不起作用。我用:
Both answer above don't work by me. I use: