Reputation: 21
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.
Upvotes: 0
Views: 1256
Reputation: 4760
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 ]]] )
Upvotes: 1