0

What's wrong with my below lines of SQL statement in PHP which causes syntax/parse error. Very simple question but I really appreciate your answers.

$sql = "SELECT * FROM my_table WHERE column1 = '$_POST["my_value"]'";

following is the error: "Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)". I changed the code according to the error(changed " to ' in $_POST or removed it for example) but again received errors. Thanks in advance for the help.

3
  • 1
    NEVER ALLOW USER INPUT TO BE INJECTED DIRECTLY INTO ANY SQL QUERY - Little Bobby Tables Commented Jul 28, 2014 at 21:36
  • 1
    Your best option to fix this is using bind variables; even if that means switching to MySQLi or PDO Commented Jul 28, 2014 at 21:37
  • RTFM? php.net/manual/en/… Commented Jul 28, 2014 at 21:54

1 Answer 1

4

The syntax you are using is indeed incorrect. Here are some options to fix the syntax:

$sql .= " column1 = '$_POST[my_value]'";
$sql .= " column1 = '{$_POST["my_value"]}'";

See the PHP documentation on string interpolation for more information.

However, note that you would be wide open to a SQL injection attack with this code. What if the user enters the text ' AND column1 = (DELETE FROM other_table) AND '? Your query becomes:

SELECT * FROM my_table WHERE column1 = ''
AND column1 = (DELETE FROM other_table)
AND ''

This may or may not do anything on MySQL, but it shows you how a user would be allowed to inject their own SQL into your query, which could allow them to do very bad things. For further reading on this topic, see the following question: How can I prevent SQL-injection in PHP?

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

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.