0

Is it possible to update a SQL column without actually defining the specific name in the query, but rather using a variable passed through function arguments?

Example

public function ScrubUserContent($db, $DBColunm, $UID, $type) {
    if($type == 1){
        mysqli_query($db, "UPDATE Users SET $DBColunm = '[ Content Deleted ]' WHERE UserID='$UID'"); // Type 1 updates strings
    } elseif($type == 2) {
        mysqli_query($db, "UPDATE Users SET $DBColunm = 'default.png' WHERE UserID='$UID'"); // Type 2 updates images
    } else {
        mysqli_query($db, "UPDATE Users SET $DBColunm = 'Missing Content' WHERE UserID='$UID'"); // Type 3 updates any other content
    }
}

I know this is possible with PDO & Dynamic SQL, but are there any alternatives?

Lachlan
  • 13
  • 6
  • and also use column enclosed by back ticks – JYoThI Jul 11 '16 at 06:22
  • When you say, "dynamic SQL", are we talking about prepared statements? As far as I know, you can't bind table or column names with prepared statements. You should hard code the column names in your query and send the values as parameters. Btw, you can do this with MySQLi as well. Not only with PDO – M. Eriksson Jul 11 '16 at 06:25
  • $DBColunm='`column_name`'; – JYoThI Jul 11 '16 at 06:25
  • Point is, I don't want to hard code them because then I wouldn't bother using a function. The point of it is that I want to pass the column name through functions so I don't have to write out unique queries every time. – Lachlan Jul 11 '16 at 06:27
  • Looks like I'll be forced to hard-code it because I can't be bothered using dynamic SQL for this. Probably just gonna have to use switch() with a ton of queries. – Lachlan Jul 11 '16 at 06:32
  • You still haven't told us what you mean by "Dynamic SQL". Regardless, neither PDO or MySQLi can use prepared statements to inject column names. You should always use Prepared Statements for you values, either way. That's the only way to really protect yourself from SQL injections. – M. Eriksson Jul 11 '16 at 06:34

0 Answers0