0

I have the following query:
SELECT * FROM ships WHERE shipCode="SP"
SELECT * FROM ships WHERE shipCode=\"SP\"

The first works fine, the second which is the result of calling mysql_real_escape_string on the first string, doesn't work and gives the useless error message #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 '\"SP\"' at line 1

What's wrong with it?

shipCode is a VARCHAR(2)

2
  • 1
    Post your PHP code. MySQL may accept single quoted strings, depending how it is configured, but single quotes are standard SQL. Commented Mar 6, 2012 at 2:00
  • You shouldn't be using mysql_* functions anymore. Use the mysqli or Pdo class instead. Commented Mar 6, 2012 at 2:09

2 Answers 2

4

You're not supposed to call mysql_real_escape_string on the whole string. You use it only on the values you're concatenating into your query.

Wrong:

$query = 'SELECT * FROM ships WHERE shipCode="' . $var . '"';
$query = mysql_real_escape_string($query);

Right:

$query = 'SELECT * FROM ships WHERE shipCode="' . mysql_real_escape_string($var) . '"';

Even better: Prepared statements.

Sign up to request clarification or add additional context in comments.

Comments

0

you need to have valid connection with mysql set up before you use mysql_real_escape string . do it like this

$attr="sp";
Select * from ships where shipcode = '" . mysql_real_escape_string($attr) . "';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.