4lisalehi
4lisalehi

Reputation: 29

PHP parse error: syntax error for sql statement

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.

Upvotes: 0

Views: 1310

Answers (1)

cdhowie
cdhowie

Reputation: 168988

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?

Upvotes: 4

Related Questions