bonaca bonaca - 4 months ago 7
SQL Question

try - catch with syntax error

try {
$stmt = $db->query('SELECT title FROM never-ending-book');
while($row = $stmt->fetch()){
echo '<div class="lev3">'.$row['title'].'</div>';
}catch(PDOException $e) {
echo $e->getMessage();


SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-ending-book' at line 1

Where is the syntax error and why is


If you happen to view the MySQL Manual it will tell you that:

Identifiers are converted to Unicode internally. They may contain these characters:

  • Permitted characters in unquoted identifiers:

    • ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)

(my bold/italics)

And because you have not quoted your column/table names with backticks then this statement (quoted above) applies.


Encase your table and column names in backticks, and/or rename them to remove characters not fitting the above specification.

Also give a careful read to the MySQL Keywords and Reserved Words listing.

  • This question does not raise any issues with PHP Try/Catch blocks.

  • It may be useful to know for future reference that when MySQL states an error, to start looking at the part of the SQL query before the quoted string, so near'-ending-book means look at the character(s) at or before '-ending-book.