未捕获异常“PDOException”消息“无效的数据源名称” [英] Uncaught exception 'PDOException' message 'invalid data source name'

查看:3397
本文介绍了未捕获异常“PDOException”消息“无效的数据源名称”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用PDO连接到我的数据库,并在一个页面上显示一些博客帖子。
但是,我收到此错误消息:

I´m trying to connect to my database with PDO and show some blogposts on a page. However I´m getting this error message:


致命错误:未捕获异常'PDOException' b数据源名称'在index.php第61行...

Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name' in index.php on line 61...

我一直在寻找帮助,找出错误所在,如果任何人有任何想法,这是非常赞赏!

I´ve been searching for help but really can´t figure out what is wrong so if anyone have any idea it is much appreciated!

我有一个单独的connect.inc.php文件,包括在index.php文件。

I have a separate connect.inc.php file which is included in the index.php file.

这是connect.inc.php文件:

This is the connect.inc.php file:

<?php
class DB extends PDO
{
function database_connection() {
   $db_host = "localhost";
   $db_name = "blogdata";
   $db_user = "username";
   $db_pass = "password";
   try {
   global $db_host, $db_name, $db_user, $db_pass;
   $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
   }
   catch(PDOException $e) {
   die( 'Query failed: ' . $e->getMessage() );
}
}
}
?>

这是index.php文件中错误消息中指出的部分: / p>

And this is the section in the index.php file which is pointed out in the error message:

<?php
    require 'connect.inc.php';  
    $db = new DB('blogdata');

    $query = "SELECT * FROM blogposts";
    if ($result = $db->query($query)) {
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        echo ' 
            <section id="content">
            <article class="post_title"><h3> ', $row['title'],' </h3></article>
            <article class="post_message"> ', nl2br ($row['message']),' </article>
            <article class="post_time"> ',$row['time'],' </article>
            </section>
            ';
        }
    } ;
    ?>


推荐答案

Gotcha。

由于某种原因,您可以从PDO中扩展课程。因此,您的blogdata被视为DSN。

For some reason you are extending your class from PDO. So, your 'blogdata' is taken as a DSN.

只需删除您的DB类并使用原始PDO

Just get rid of your DB class and use raw PDO

connect.inc.php:

<?php 
$db_host = "localhost";
$db_name = "blogdata";
$db_user = "username";
$db_pass = "password";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

index.php:

<?php
require 'connect.inc.php'; 

$query = "SELECT * FROM blogposts";
$result = $db->query($query);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {

这篇关于未捕获异常“PDOException”消息“无效的数据源名称”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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