0

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.

5
  • 1
    For now, you haven't selected a database. php.net/manual/en/pdo.construct.php Commented Jan 11, 2016 at 10:40
  • Yes, but even If I had still same error Commented Jan 11, 2016 at 10:47
  • 1
    Please edit the code to its final version, with the selected db and all Commented Jan 11, 2016 at 10:48
  • How do people expect to get correct responses when the code they post is not complete? Commented Jan 11, 2016 at 10:50
  • Tip (for both OP and commenters): if you have an error in a given line of code, the error cannot be caused by the lines of code that execute afterwards. Commented Jan 11, 2016 at 11:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Be sure to use the checkbox to accept the answer since it resolves your question, thank you
It tells me that I can't give +1 because I haven't got 15 reputation.
You can click the checkbox and out will accept the answer. The checkbox is below the down vote arrow,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.