我正在尝试使用PDO连接到我的数据库并在页面上显示一些博客帖子.
但是我收到此错误消息:
但是我收到此错误消息:
Fatal error: Uncaught exception ‘PDOException’ with message ‘invalid
data source name’ in index.PHP on line 61…
我一直在寻求帮助,但真的无法弄清楚出了什么问题,所以如果有人有任何想法,我们非常感谢!
我有一个单独的connect.inc.PHP文件,它包含在index.PHP文件中.
<?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_pass); } catch(PDOException $e) { die( 'Query Failed: ' . $e->getMessage() ); } } } ?>
<?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> '; } } ; ?>
疑难杂症.
原文链接:https://www.f2er.com/php/138945.html出于某种原因,您正在从PDO扩展您的课程.所以,你的’blogdata’被视为DSN.
只需摆脱您的数据库类并使用原始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_pass); $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
<?PHP require 'connect.inc.PHP'; $query = "SELECT * FROM blogposts"; $result = $db->query($query); while ($row = $result->fetch(PDO::FETCH_ASSOC)) {