Why does this query throw an error

So i have a query as a separate string so i can just active it on the database and so its easier to change ect.I have a database with some random data in it.
The table was created by the following statement:
CREATE TABLE todolist( descvarchar(255) COLLATE utf8_unicode_ci NOT NULL, user varchar(255) COLLATE utf8_unicode_ci NOT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The desc is used to store the description of the task and the user is used to tie the user(from a user account system) to their todo list. Because of the data in the session i can get the logged users username.
The error comes from the following statement:
$uname = $_SESSION[‘user’][‘username’];
// Query for the todo list
$query = "
SELECT desc
FROM todolist
WHERE user = $uname
";

try
{
    // Run the query
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
}
catch(PDOException $ex)
{
    echo $query;
    //die("Failed to run query");
    die("Failed to run query: " . $ex->getMessage());
}

Here i am using the query to get all of the desc’s from the database under the users username(From the session)
For some reason it throws and error and it reads as follows:
SELECT desc
FROM todolist
WHERE user = Matthew
Failed to run query: 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 ‘desc
FROM todolist
WHERE user = Matthew’ at line 1
Any help?

I think the issue is that user is a MySQL reserved word, so you need to put quotes around it. https://dev.mysql.com/doc/refman/5.7/en/identifiers.html

ETA : Doh! And of course, desc is also a reserved word in MySQL for specifying descending sort order, so you’ll have to quote that as well. That’ll be why the error message says “Syntax error near 'desc” instead of “near 'user”.

1 Like

Thanks mate! All fixed up

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.