简体   繁体   中英

SQL Statement is giving me an error, It appears fine although

The following is my PHP code

$till=2;
$tilll=$till + 5;

$result = mysql_query("SELECT * FROM test where id >=".$till."AND id <= ".$tilll)

When i run it i get the following message

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 'id <= 7' at line 1

i dont know whats wrong with it ?

If you try displaying your query, I think you would see the error. The SQL probably looks something like this:

SELECT * FROM test where id >=2AND id <= 7

You are missing a space before AND. Try this:

$result = mysql_query("... id >=".$till." AND id <= ".$tilll)
#                                        ^ extra space here

You also need to terminate the PHP statement with a semi-colon. I assume you are doing this and just forgot to post it, but it would be a good idea to double-check that there is a semi-colon in the correct place.

I'd also suggest that you use BETWEEN instead of id >= ... AND id <= ... , and that you give your variables sensible names:

$sql = "SELECT * FROM test WHERE id BETWEEN " . $min_id . " AND " . $max_id;
$result = mysql_query($sql);
if ($result) {
    # Read results.
} else {
    # Handle error.
}

AND之前缺少空格

For debugging things like this, it makes sense to save the query to a string first, and dump it before executing it.

$query = "SELECT ...";
print "Query: '$query'";
$result = mysql_query($query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM