PHP-PDO连接字符串中未替换的变量 [英] PHP - Variables not replaced in PDO connection string

查看:71
本文介绍了PHP-PDO连接字符串中未替换的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的问题-我有一个正常工作的数据库类的实时副本(使用PDO).我在使用WAMPServer的计算机上有一个副本,但没有.

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);

我收到的错误消息是:

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);

谢谢:)

推荐答案

使用双引号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

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

这篇关于PHP-PDO连接字符串中未替换的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆