似乎是什么问题,因为我的凭据是正确的,当我使用mysqli oop
时它确实连接但在我使用pdo
时失败了。我使用000webhost作为我的自学ftp网站。我一直在寻找答案,但似乎无法自己解决。
错误:
连接错误:SQLSTATE [28000] [1045]拒绝用户访问 ' a1882281_user' @'本地主机' (使用密码:是)
当我的主机是mysql9.000webhost.com时,为什么localhost在那里?
它不应该显示' a1882281_user' mysql9.000webhost.com'?
// mysqli oop, working
<?php
$host = "mysql9.000webhost.com";
$username = "a1882281_user";
$password = "********"; //my password is all numbers
$db = "a1882281_db";
$conn = new mysqli($host, $username, $password, $db);
if(!$conn){
echo "error connecting: " . $conn->error;
}
$sql = "SELECT firstname FROM Friends";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
echo $row['firstname'];
}
$result->free();
$conn->close();
?>
// pdo, cannot connect :(
<?php
$host = "mysql9.000webhost.com";
$username = "a1882281_user";
$password = "********"; //my password is all numbers
$db = "a1882281_db";
try{
$conn = new pdo("mysql:host = $host; dbname = $db", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $ex){
echo "connect error: " . $ex->getMessage();
}
?>
答案 0 :(得分:1)
您的错误与内部字符串中存在的空格有关:
$conn = new PDO("/*...string inside here...*/", $username, $password);
以下完整代码应该可以正常工作:
<?php
$host = "mysql9.000webhost.com";
$username = "a1882281_user";
$password = "********"; //my password is all numbers
$db = "a1882281_db";
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>