Saturday 16 February 2019

php - 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:



    $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'];
}
?>

Answer



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'


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...