0
I am mounting a code to make comments but the connection to the database is outside the function, so it is necessary to put the code inside the function, as I pull the code that is outside?
include 'sis-config.php';
include 'sis-checar.php';
$conn = mysqli_connect($host, $usuario, $senha, $db);
if (!$conn) {
echo "Não foi possível conectar-se ao MySql." . PHP_EOL;
exit;
}
function comentar()
{
include 'sis-config.php';
$conn = mysqli_connect($host, $usuario, $senha, $db);
if (!$conn) {
echo "Não foi possível conectar-se ao MySql." . PHP_EOL;
exit;
}
if (isset($_POST['comentar']))
{
$nome=$_POST['nome'];
$msg=$_POST['mensagem'];
$vrc1=checar($nome);
$vrc2=checar($msg);
$ip=$_SERVER['REMOTE_ADDR'];
$p = "INSERT INTO `chat` (`nome`, `ip`, `mensagem`, `vip`) VALUES ('$vrc1', '$ip', '$vrc2', '0');";
if ($conn->query($p) === TRUE) {
echo 'Postado com sucesso';
} else {
echo "Erro: " . $p . "<br>" . $conn->error;
}
}
}
When I remove the
include 'sis-config.php';
$conn = mysqli_connect($host, $usuario, $senha, $db);
if (!$conn) {
echo "Não foi possível conectar-se ao MySql." . PHP_EOL;
exit;
function, query does not work, I want it to work without having to put the code inside the function
Thank you very much
– Victor Stanford
@Victorstanford I recommend you also read about the one-time responsibility principle as it will help you write more consistent functions.
– Woss