我正在尝试使用 PDO 创建博客,问题是当我转到应该列出我的文章的索引文件时,出现此错误。
C:\wamp\www\simpleblog\includes\config.php 中带有消息的未捕获异常 'PDOException'
PDOException: SQLSTATE[HY000] [2002] 由于目标机器主动拒绝,无法建立连接。在第 11 行的 C:\wamp\www\simpleblog\includes\config.php
我对 PDO 很陌生,所以我无法弄清楚可能导致问题的原因。我查看了其他问题,但找不到与此类似的任何问题。我检查了 phpmyadmin 并且数据库名称是正确的。
这是我的 index.php
<?php require('includes/config.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Blog</title>
<link rel="stylesheet" href="style/normalize.css">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div id="wrapper">
<h1>Blog</h1>
<hr />
<?php
try {
$stmt = $db->query('SELECT postID, postTitle, postDesc, postDate FROM blog_posts ORDER BY postID DESC');
while($row = $stmt->fetch()){
echo '<div>';
echo '<h1><a href="viewpost.php?id='.$row['postID'].'">'.$row['postTitle'].'</a></h1>';
echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).'</p>';
echo '<p>'.$row['postDesc'].'</p>';
echo '<p><a href="viewpost.php?id='.$row['postID'].'">Read More</a></p>';
echo '</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
</div>
</body>
</html>
还有我的 config.php
<?php
ob_start();
session_start();
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','blog');
$db = new PDO("mysql:host=".DBHOST.";port=80;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//set timezone
date_default_timezone_set('Europe/London');
//load classes as needed
function __autoload($class) {
$class = strtolower($class);
//if call from within assets adjust the path
$classpath = 'classes/class.'.$class . '.php';
if ( file_exists($classpath)) {
require_once $classpath;
}
//if call from within admin adjust the path
$classpath = '../classes/class.'.$class . '.php';
if ( file_exists($classpath)) {
require_once $classpath;
}
//if call from within admin adjust the path
$classpath = '../../classes/class.'.$class . '.php';
if ( file_exists($classpath)) {
require_once $classpath;
}
}
$user = new User($db);
?>