Reputation: 27
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?
Upvotes: 1
Views: 2607
Reputation: 13475
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);
Upvotes: 3