Thiagosilr’s answer is correct, just put the variable names inside the string with double quotes. However, I suggest not using this method to form darlings to be executed at your bank, as it makes you vulnerable to SQL injection attacks.
For example, if the user has control of the variable content $assunto
through a form, could fill it as '1'); DROP DATABASE ...
and try to destroy your bank only of pirraça.
A way to execute that same INSERT
ensuring that input variables do not cause damage is using prepared statements
, as demonstrated in the responses to this question from the SOE.
So, if you are using Mysqli, you instantiate an object of statement using the method prepare()
of your connection object, specifying the gaps for parameters of bind using question marks, then pass the parameters in order in the method bind_param()
of statement finally executes it:
//cria o statement
$statement = $dbConnection->prepare("INSERT INTO $tabela (data, assunto, destino, elaborado) VALUES(?, ?, ?, ?)");
//passa as variáveis para preencher os pontos de interrogação
//o parametro 's' significa que você está passando uma string. É como um printf...
$statement->bind_param('s', $data);
$statement->bind_param('s', $assunto);
$statement->bind_param('s', $destino);
$statement->bind_param('s', $elaborado);
//executa o statement
$stmt->execute();
Note that a Prepared statement only supports the parameterization of values of a query. Thus, the table name variable must be passed with simple string concatenation as in Thiago’s answer. I imagine it is somewhat unlikely that such a variable is an attack vector, since it is unusual to allow the user of an application to decide on which table of the system you want to query.
This answers your question? How to prevent SQL code injection into my PHP code?
– Icaro Martins