我是php的新手。我一直无法通过PHP连接和使用数据。我已经仔细检查并查看了这个网站上的信息,但我找不到多少。这是下面的错误和代码。
我正确输入了用户名和密码。我甚至创建了一个新的用户名和密码,以确保。我没有其他想法为什么它不会连接到我的localhost。我很乐意看到有关可能的错误和感谢的任何反馈!
错误如下:
警告:PDO :: __ construct():php_network_getaddresses:getaddrinfo failed:没有这样的主机。在第26行的C:\ xampp \ htdocs \ website \ Practice \ mysqli \ connection.inc.php
致命错误:未捕获的异常'PDOException',消息'SQLSTATE [HY000] [2002] php_network_getaddresses:getaddrinfo failed:没有这样的主机是已知的。 '在C:\ xampp \ htdocs \ website \ Practice \ mysqli \ connection.inc.php:26堆栈跟踪:#0 C:\ xampp \ htdocs \ website \ Practice \ mysqli \ connection.inc.php(26):PDO - > __ construct('mysql:host = $ hos ...')#1 C:\ xampp \ htdocs \ website \ Practice \ mysqli \ pdo.php(5):dbConnect('read')#2 {main}在第26行的C:\ xampp \ htdocs \ website \ Practice \ mysqli \ connection.inc.php中抛出 $ result = $ conn-> query($ sql)或die(mysqli_error());
connection.ini.php
function dbConnect($usertype, $connectiontype = 'mysqli') {
$host = 'localhost';
$db = 'student';
if ($usertype == 'read') {
$user = 'user';
$pwd = 'pass';
}
elseif ($usertype == 'write') {
$user = 'root';
$pwd = 'password';
}
else {
exit('Unrecognized connection type');
}
//Connection Code
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
else {
try {
return new PDO('mysql:host=$host;dbname=$db, $user, $pwd');
}
catch(PDOExecption $e) {
echo 'Cannot connect to database';
exit;
}
}
}
?>
mysqli.php
?php
require_once('connection.inc.php');
$conn = dbConnect('read');
$sql = 'SELECT * FROM guestbook';
$result = $conn->query($sql)or die(mysqli_error());
$numRows = $result->num_rows;
?>
<!DOCTYPE html>
<html>
<p> A total of <?php
echo $numRows;
?>
records were found.</p>
</html>
答案 0 :(得分:2)
function dbConnect($usertype, $connectiontype = 'mysqli') {
$host = 'localhost';
$db = 'student';
if ($usertype == 'read') {
$user = 'user';
$pwd = 'pass';
}
elseif ($usertype == 'write') {
$user = 'root';
$pwd = 'password';
}
else {
exit('Unrecognized connection type');
}
//Connection Code
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
}
catch(PDOException $e) {
echo 'Cannot connect to database';
exit;
}
}
}
?>
您正在使用
return new PDO('mysql:host=$host;dbname=$db, $user, $pwd');
但是你需要使用双引号来使用
之类的变量return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
或者你可以使用它:
return new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
您可以在此处查看更多内容:Pdo Connection和 Variable inside double quotes
答案 1 :(得分:1)
单引号括起的字符串未被解析,因此其中的变量不会被其值替换。在DSN字符串中使用双引号而不是单引号:
return new PDO("mysql:host=$host;dbname=$db, $user, $pwd");