Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

php - Uncaught exception 'PDOException' message 'invalid data source name'

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

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!

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

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() );
}
}
}
?>

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>
            ';
        }
    } ;
    ?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Gotcha.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...