0

In the following code $keyresult and $valueresult are comma separated lists of columns in my db and the values I want to put into them in the identified row. The problem is, the code isn't doing what I hoped it would and is returning a syntax error in the query.

$q3 = "UPDATE post SET ($keyresult) VALUES ('$valueresult') WHERE user_id='$user_id' AND post_id='$post_id' AND post_status='active'";

How can I fix the syntax of this?

1 Answer 1

3

You are mixing INSERT and UPDATE syntax.

$q3 = "UPDATE `post` SET `$keyresult` = '$valueresult' 
       WHERE user_id='$user_id' AND post_id='$post_id' AND post_status='active'";

I am assuming you are properly escaping $valueresult, $user_id, and $post_id before you are executing your query. If not, and these are user-supplied values, you are wide open to SQL injections. I recommend looking into prepared statements to eliminate this risk.

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

2 Comments

THe problem with this is that the $keyresult variable contains multiple columns (column 1, column 2, column 3) and the $valueresult has corresponding values (value 1, value 2, value 3). Running it like this gives a syntax error as well. And yes. They are escaped with mysqli_escape_string
Then you need to generate your query differently. The way you are approaching it won't work. A simple loop would make this simple.

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.