开发者

SQL is breaking on a character I didn't put in my code

I'm getting a syntax error on this PHP code:

<snip>
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;

$query = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') AS post_time" . 
    " FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last . ";";

$message_query = db_query($query);
</snip>

And db_query:

开发者_开发知识库function db_query($query, $link = 'db_link') {
    global $$link;

    $result = mysql_query(mysql_real_escape_string($query), $$link) or db_error($query, mysql_errno(), mysql_error());

    return result;
}

The exact error is this:

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 '\' %h:%i\') 
AS post_time FROM message WHERE chat_id = 1 AND message_id > 0' at line 1<br><br>
SELECT message_id, user_name, message, date_format(post_time, '%h:%i') AS 
post_time FROM message WHERE chat_id = 1 AND message_id > 0;

As you can see, it's throwing an error on a character that I don't have/see in my code. What is going on here?


You need to use mysql_real_escape_string only on your variables, not on the whole sql query.

Now it is translating:

date_format(post_time, '%h:%i')

to:

date_format(post_time, \'%h:%i\')

By the way, I´m assuming that your db_input function prepares your variables for use with a database, so you definitely need to use that for your $last variable as well.


Try this:

$query = "SELECT message_id, user_name, message, " . 
date_format(post_time, '%h:%i') . "AS post_time" . " FROM message 
WHERE chat_id = " . db_input($_GET['chat']) . "AND message_id > " . $last . ";";

Try to call date_format outside the string " . date_format(post_time, '%h:%i') . "

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜