Close connection to the database

0

I would like to know if anyone could get me the following question, I connect to the database in PHP like this:

$conexao = new mysqli($servidor, $usuario, $senha, $nomeBanco);

And I close the connection with $conexao->close(); . If I use $conexao->query($sql) multiple times on my page do I need a $conexao->close(); for each one or does this method already hold all calls?

    
asked by anonymous 16.09.2018 / 04:03

1 answer

3
  

If I use $conexao->query($sql) multiple times on my page it's   a $conexao->close(); is required for each or this method already   does it handle all calls?

You do not need to close the connection for every $conexao->query($sql) . So, why do not you think of me, if I open a connection and run a query and right after the connection already close, if I try to run another query for not having an open connection to the database.

To illustrate, imagine a random database. Let's open a connection to it, display the data, run a query , close the connection and try to run another query .

$conexao = mysqli_connect('localhost', 'usuario', 'senha', 'banco');

var_dump($conexao); // Mostrará alguns dados da conexão

mysqli_query($conexao, "INSERT INTO tabela (coluna) VALUES ('Teste')");

mysqli_close($conexao); // Fecho a conexção

mysqli_query($conexao, "INSERT INTO tabela (coluna) VALUES ('Teste depois da conexão')");
When I run the first query I will succeed and the value will be inserted, since the second query will not be inserted and will return a warning :
  

Warning: mysqli_query (): Could not fetch mysqli in (path) on line

Just remembering: mysqli_close closes a previously opened connection to the database and always returns TRUE in success and FALSE in failure .

References

16.09.2018 / 05:52