Close connection to the database

Asked

Viewed 1,149 times

0

I wonder if anyone could ask me the following question, I make the connection to the database in PHP this way:

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

And close the connection with $conexao->close();. If I use $conexao->query($sql) several times on my page it is necessary a $conexao->close(); for each or that method already holds all calls?

  • Erick, if any answer has solved your problem you can mark as accepted by clicking on the green V side of the chosen points. Or, if you want, you can leave it open for a while if you want more alternatives, but it is good that after it is resolved you mark some to close the subject. Learn more in "How and why to accept an answer".

  • 1

    Thank you very much my friend! Your contribution was of great help!

1 answer

3


If I use $conexao->query($sql) several times on my page is necessary a $conexao->close(); for each method already holds all calls?

No need to close the connection for each $conexao->query($sql). Because, think to me, if I open a connection and run a query and soon after the same already close the connection, if I try to run another query PHP will show error by precisely not having open connection to the database.

To illustrate imagine an allegorical database. Let’s open a connection with it, show the data, run a query, close the connection and try to run another again 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 executing the first query I will succeed and the value will be inserted, the second query will not be inserted and will return a Warning:

Warning: mysqli_query(): Couldn’t fetch mysqli in (path) online (line)

Just remembering: the mysqli_close closes a previously opened connection to the database and always returns TRUE on Success and false in the Failure.

References

Browser other questions tagged

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