1

I am trying to echo all the values of 'comment' from a user defined table ($table_name)

$pdo = new PDO('mysql:dbname=db', 'user', 'pass');

$stmt2 = $pdo->query("SELECT comment FROM '$table_name'");

    if ($stmt2->rowCount() > 0) {

        $comments = $stmt2->fetchAll(PDO::FETCH_NUM);

        foreach ($comments as $comment) {

            $comm = $comment[0];
            echo $comm;

        }
    }


However I get this error:

Fatal error: Call to a member function rowCount() on a non-object in /FilePath/file.php on line 3

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Locke Donohoe
  • 482
  • 1
  • 7
  • 22
  • 3
    You have single quotes around the table name. Remove them. This is a typographical error and I'm voting to close. – Gordon Linoff Sep 23 '14 at 02:47
  • 2
    Add `$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` right after the connection is opened. This will signal errors found. Plus add error reporting to the top of your file(s) right after your opening ` – Funk Forty Niner Sep 23 '14 at 02:47

1 Answers1

1

No identifier quotes are backticks not single quotes.

`backticks`

// not 'table_name'
       ^ single quotes

Just take out that quotes. It will work just fine.

$stmt2 = $pdo->query("SELECT comment FROM $table_name");

Unless, as @Fred stated, your table name is a MySQL reserved word or has spaces or a hyphen (or any other character that SQL will disagree with), then you need to have them.

And as always, turn on error reporting.

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // below the pdo connection
error_reporting(E_ALL);
ini_set('display_errors', '1');
// first lines of the file
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Kevin
  • 41,694
  • 12
  • 53
  • 70