MySQL Forums
Forum List  »  PHP

Re: Syntax Error - Syntax for 'LIMIT 1'
Posted by: Rick James
Date: July 25, 2012 09:47AM

Jose, you will have unbalanced apostrophes.

Let's walk it through the steps (using the correct code):
1. $query .= "WHERE id='" .mysql_real_escape_string($subject_id) . "' ";
2. $query .= "WHERE id='" . "1234" . "' ";
3. $query .= "WHERE id='1234' ";
4. $query = "SELECT * FROM subjects WHERE id='1234' ";

2 -- the function call is evaluated and the result (the string "1234" is put in its place.
3 -- do the '.' operator; that is 'concatenate' the strings
4 -- do the ".="
The result is valid SQL:
SELECT * FROM subjects WHERE id='1234' LIMIT 1
Note: MySQL won't see the double-quotes; that is still PHP syntax.

Either of these will work (in this case!):
WHERE id='1234'
WHERE id=1234
This is because id is an INT (a number), and MySQL is forgiving about comparing INT with a quoted number.

To end up with WHERE id=1234, start with
$query .= "WHERE id=" .mysql_real_escape_string($subject_id);

Hmmm... That is very close to the first posting:
$query .= "WHERE id=" . $subject_id ." ";
$query .= "LIMIT 1";
which should have worked. Here is an equivalent phrasing, that uses "interpolation":
$query .= "WHERE id=$subject_id ";
$query .= "LIMIT 1";
Now, isn't that simpler than all the quotes and "."s?
What the heck, do
$query = "SELECT * FROM subjects WHERE id=$subject_id LIMIT 1";
That makes it much more obvious what the resulting SQL will be.

Going back to the original, note how there were spaces at the end of each string? Without them, you might get
SELECT *FROM subjectsWHERE id='1234'LIMIT 1
which would give you syntax errors.

I agree that that tutorial has issues; I can see a few more in that one example. Finish it fast, get familiar with the online docs for PHP and MySQL, and switch from mysql_* to mysqli_* or PDO.

Options: ReplyQuote


Subject
Written By
Posted
Re: Syntax Error - Syntax for 'LIMIT 1'
July 25, 2012 09:47AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.