I am working on a PHP application based on MS SQL that, among other things, can add a column to a table, either bit, int or varchar. My current code is similar to this:
$sql = "ALTER TABLE myTable ADD ? ".$type;
$values = array($columnname);
if($type == "varchar")
$sql = $sql."(".$length.")";
$sql = $sql.";";
sqlsrv_query($conn, $sql, $values);
However, I only get back an error that tells me there's an incorrect syntax near '@P1'. I thought about inserting the column name into the string directly, but I'm afraid of SQL injection as it is a text input. I'm not as worried about it for the type and the length as those are a select and a number input.
I am hoping one of you can give me some advice on how to add the column without exposing myself to SQL injection. Thank you in advance!
(As this question has been marked a 'possible duplicate' I'd like to clarify that I'm specifically asking about adding a new column without exposing myself to SQL injection, not just inserting values into a table. I hope I made this clear.)