Ronalds Mazītis
Ronalds Mazītis

Reputation: 341

PDO sql syntax wrong?

I have db named CMS with two columns: id and data1

I get following error for the code below when trying to fetch data from the database.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table' at line 1' in /var/pdo/index.php:4 Stack trace: #0 /var/pdo/index.php(4): PDO->query('SELECT * FROM t...') #1 {main} thrown in /var/pdo/index.php on line 4

Why am I getting this error?

This is my code:

<?php
    $db = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'root', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $stmt = $db->query('SELECT * FROM table');

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['field1'];
    }
?>

Upvotes: 0

Views: 248

Answers (1)

GuyT
GuyT

Reputation: 4416

table is a reserved word. See http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html for the full list.

You could use backticks (SELECT * FROM `table`) if you still want to use your tablename 'table'

Upvotes: 7

Related Questions