Run addslashes function on all Insert fields

Asked

Viewed 101 times

2

I am using the PHP code below to make an Insert in the Mysql database:

$sql = "INSERT INTO acolhidos
(
situacao,
nome,
dataNasc,
nacionalidade,
naturalidade,
cidadeNasc,
cpf,
...
updateLogin
)
VALUES
(
'$dados[situacao]',
'$nome',
'$dataNasc',
'$dados[nacionalidade]',
'$dados[naturalidade]',
'$dados[cidadeNasc]',
'$dados[cpf]',
 ...
'$_SESSION[cc_login]'
)";
$acolhido = mysqli_query($conn->link, $sql);

Being that the complete list of inserted fields is around 80, so I listed above just a few fields as example.

To avoid that, in String type fields, the INSERT fails if the user has inserted single (') or double quote characters (") in the form entry, I am using the addslashes function in all fields of the string type before mounting the Insert string, as below:

$dados['aspectoFisico'] = addslashes($dados['aspectoFisico']);
$dados['aspectoEmocional'] = addslashes($dados['aspectoEmocional']);
$dados['aspectoPsiquico'] = addslashes($dados['aspectoPsiquico']);
$dados['aspectoSocioCom'] = addslashes($dados['aspectoSocioCom']);
$dados['outrasObservacoes'] = addslashes($dados['outrasObservacoes']);

That is, I’m having to repeat the same function for almost all fields of my Insert.

Then I would like to know if there is a more practical way to run this addslashes function in all fields of my Insert before running the SQL command?

Or maybe a way to run addslashes directly on my $sql string without damaging the contents of the sql command?

1 answer

2


Makes a foreach() before adding the addslashes():

foreach ($dados as $key => $value) {
    $dados[$key]=addslashes($value);
}
  • in the above case addslashes does not damage the variable if it is numerical or if it is a date? Because some of the $data array fields will be of type numere or date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.