1

I need to make a SQL update statement in php, and my column name need to be a variable. I get these variables from jQuery ajax post method and i have them in PHP :

$variable = $_POST['variable']; 
$row = $_POST['row']; 
$field = $_POST['field'];  

When i echo them out, i get the right values, for example:

echo $variable; 
echo $row;
echo $field;

And i get - martins, 2, firstname. In my database i have column with name - firstname. So, i try to make this statement ( i know that i need to use prepared statement, but that is another question)

$sql = 'UPDATE ajax_example SET '.$field.'= "'.$variable.'" WHERE id = "'.$row.'"';
mysql_query($sql) or die (mysql_error());

If i change '.$field.' with name - firstname, then UPDATE is successful, so $variable and $row is defined correctly , but i need this column name as variable. I have seen about 15 posts, and i have tried each of hose codes but nothing. Is that realy impossible?

3
  • Escape your input variables, and please don't use mysql_ functions anymore, use mysqli_ or PDO Commented Feb 16, 2014 at 18:07
  • 1
    1. Don't use mysql_. They're deprecated (and have been for a couple of years). Use mysqli_ or PDO. Second of all, this code is insanely insecure. Commented Feb 16, 2014 at 18:07
  • 1
    Please, please, escape your input variables. Passing them directly into the statement will open doors for a classical attack, called "SQL injection". Commented Feb 16, 2014 at 18:07

1 Answer 1

3

You need to escape your variables, a basic example given your context...

$conn = mysqli_connect(/* config */);
$sql = 'UPDATE ajax_example SET ' . mysqli_real_escape_string($conn, $field).'= "' . mysqli_real_escape_string($conn, $variable) . '" WHERE id = "' . mysqli_real_escape_string($conn, $row) . '"';
mysqli_query($conn, $sql);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! This works! :) But why escape is so necessary? And shoud i use PDO? PDO have some very big pluses?
@user3316619 Prepared statements are always better than pasting variables into your query. See Is mysql_real_escape_string sufficient for cleaning user input.
@h2ooooooo mysql_real_escape_string isn't sufficient, but mysqli_real_escape_string is fine - because it escapes against the connection that you provide it - whereas the mysql_ variation does not - PDO is far better, but it's a huge deviation from what the OP has

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.