With pulling a variable out of the PHP function

Asked

Viewed 30 times

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

1 answer

0


Pass by parameter:

function comentar($conn) {
  ...
}

And when you call the function, do comentar($conn). That’s why there are function parameters, manage scopes.

  • Thank you very much

  • @Victorstanford I recommend you also read about the one-time responsibility principle as it will help you write more consistent functions.

Browser other questions tagged

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