简体   繁体   中英

PHP $db PDO connection error

I wanted to make posts and comments system.
Posts worked fine, but comments had

PHP error: Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name' in C:\xampp\htdocs\index.php:133 Stack trace: #0 C:\xampp\htdocs\index.php(133): PDO->__construct('localhost', 'root', '') #1 {main} thrown in C:\xampp\htdocs\index.php on line 133. `

$db = new PDO ("localhost", "root", "");
$query = $db->prepare("SELECT * FROM comments");
$query->execute();
while($fetch = $query->fetch(PDO::FETCH_ASSOC)){
    $name = $fetch['name'];
    $message = $fetch['comment'];
    echo "<li class='com'><b>".ucwords($name)."</b> - ".$message."</li>";
}

It's element of table. Please help.

You need to specify a DSN when instantiating, replace testdb with the name of your database.

Change localhost to something like this mysql:dbname=testdb;host=127.0.0.1 .

$db = new PDO ("mysql:dbname=testdb;host=localhost", "root", "");
$query = $db->prepare("SELECT * FROM comments");
$query->execute();
while($fetch = $query->fetch(PDO::FETCH_ASSOC)){
    $name = $fetch['name'];
    $message = $fetch['comment'];
    echo "<li class='com'><b>".ucwords($name)."</b> - ".$message."</li>";
}

Read more here: http://php.net/manual/en/pdo.construct.php

Usage : public PDO::__construct ( string $dsn [, string $username [, string $password [, array $options ]]] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM