开发者

MySQL syntax error in selecting multiple columns with the WHERE delimiter?

开发者 https://www.devze.com 2023-04-07 03:10 出处:网络
I have a rather simple query to work with my ajax app, but it gives the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the

I have a rather simple query to work with my ajax app, but it gives the following error:

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, price FROM products WHERE id='asfasfasf1'' at line 1

I'm stumbled by this as I simply can't see the syntax error anywhere:

echo json_encode($this->query("SELECT name, desc, price FROM products WHERE id='".$id."';"), JSON_FORCE_OBJECT);

query() is as follows:

function query($query){
        $link = mysql_connect($this->host, $this->username, $this->password);
        $connected = mysql_select_db($this->database, $link);
        if(!$connected){
            die("Error: selecting database.");
        }
        $q = mysql_query($query);
        if(!$q){
            return "Error: ".mysql_error();
        }
        $result = mysql_fetch_assoc($q);
        return $result;
    }

Naturally, this is inside an object, but that shouldn't have anything to do with it. All 开发者_运维百科the fields are correct, database can be connected to since the query() is used multiple times with other code and works well. Please help.


desc is a keyword in SQL (for sorting in descending order.) If you're going to use it as a column name, try quoting it:

$this->query("SELECT name, `desc`, price FROM products WHERE id='".$id."';")

See the MySQL manual on reserved words for an almost identical example, and more details on how to deal with keywords.

Or you could just rename your column to "description", say. Much as quoting is the "right" solution, it's generally helpful to avoid using reserved words as column names if you can.


There's a good chance id has to be in double quotes, not single ones.

BTW, be careful with this sort of thing because it makes SQL injection attacks really easy.

0

精彩评论

暂无评论...
验证码 换一张
取 消