Search code examples
phpmysqldatabaseconcatenation

Using mysql's CONCAT() for a column name


I want to UPDATE a database column by concatenating a string with a function. let's say that I have two columns sum_likes_c1 and sum_likes_c2 and I have a function called $class has 1 or 2 value

so I want the query to update the column based on $class value

my current code (not working):

if (isset($function)) {
    $class = 1;
    } else $class = 2;

    $update_likes = mysqli_query($con, "UPDATE posts SET CONCAT(sum_likes_c,'$class') ='$total_likes' WHERE id='$post_id'");

Any help would be appreciated


Solution

  • CONCAT() is a string function, you cannot use it for column names which are identifiers. You have to concatenate in PHP. See how to do it properly

    That said, if you need to concatenate to get a coulmn name, most likely (like 99%) your database design is wrong. There must be a separate table to collect your likes, preferably using INSERT, not UPDATE