Update the column value according to the PHP variable that is equal to a column name

advertisements
$rating =  mysqli_real_escape_string($conn,$_POST['rating']);
$id = mysqli_real_escape_string($conn,$_POST['id']);
mysqli_query($conn,"UPDATE table SET $rating=$rating+1 WHERE id='$id'");

Is there any way to update a column based on the PHP variable $rating? $rating is a column name.

Also, this may be prone to security risks etc, so I'd like to know if this is even a good way to go about it.


Yes you can use variable name as field name in the sql. However you must validate it first before putting it into sql string. Since its not a field value, you cannot "quote" it.

$rating =  $_POST['rating'];
// Define list of valid "rating" db field names here
$valid_fields = Array('rating_a', 'rating_b', 'rating_c');

if (in_array($rating, $valid_fields)) {
    $id = mysqli_real_escape_string($conn,$_POST['id']);
    mysqli_query($conn,"UPDATE table SET $rating=$rating+1 WHERE id='$id'");
}