How to put a php variable in a mysql query?

0

For example:

$query = "INSERT INTO tabela (data, assunto, destino, elaborado) VALUES('{$data}', '{$assunto}', '{$destino}', '{$elaborado}')";

Where is tabela , I want to put a variable in place, because depending on what the user chooses, will use a different table.

I have tried with quotation marks, with dot, with keys ...

    
asked by anonymous 21.06.2018 / 00:16

2 answers

3

In PHP when you have a string surrounded by double quotation marks. The PHP interpreter will go through it and check if it has no variables to replace.

<?php
$tabela = 'Tabela1';
$data = '2018-06-20';
$assunto = 'Assunto';
$destino = 'Destino';
$elaborado = 'Elaborado';

$query = "INSERT INTO $tabela (data, assunto, destino, elaborado) 
VALUES('$data', '$assunto', '$destino', '$elaborado')";

echo $query;

The echo $query; excerpt will print INSERT INTO Tabela1 (data, assunto, destino, elaborado) VALUES('2018-06-20', 'Assunto', 'Destino', 'Elaborado')

    
21.06.2018 / 00:58
0

Thiagosilr's answer is correct, just put the variable names inside the string with double quotation marks. However, I suggest not using this method to form queries to run on your bank, as it makes you vulnerable to SQL injection attacks .

For example, if the user has control of the contents of the $assunto variable through a form, he could fill it as '1'); DROP DATABASE ... and try to destroy his bank just from pissing.

One way to execute this same INSERT ensuring that the input variables do not cause damage is by using prepared statements , as demonstrated in the responses to this SOE question .

So if you are using MySQLi, you instantiate a statement object using the prepare() method of your connection object, specifying gaps for bind parameters using question marks, then passes the parameters in order in the% method of the statement and 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 an prepared statement only supports parameterizing the values of a query. Thus, the table name variable must be passed with simple string concatenation as in Thiago's response. I imagine it is unlikely that such a variable is an attack vector, since it is somewhat unusual to allow the user of an application to decide which system table to look at.

    
21.06.2018 / 19:10