1

I have a PHP document which contains mostly html, but also some MySql queries which look like this:

<?php
require_once('connectdata.php');

$db = mysqli_connect(DB_HOST, DB_BENUTZER, DB_PASSWORT, DB_NAME);

$myquery = "SELECT name FROM Entries WHERE typ = 'Communication' ORDER BY name";

$result = mysqli_query($db, $myquery);

while($row = mysqli_fetch_object($result))
 {
 echo "$row->name";

 }

mysqli_close($db);

I am using this exact code several times in my document to echo the data I want to display. Is this a good practice or is there a way to just connect once get all the data and echo them later in the document?

Is it bad if I leave it like that?

1

1 Answer 1

2

You already have your connection. When you have to make a query just use the syntax:

$myquery = "SELECT name FROM Entries WHERE typ = 'Communication' ORDER BY name";

You can include :

$db = mysqli_connect(DB_HOST, DB_BENUTZER, DB_PASSWORT, DB_NAME);

in your connectdata.php file, which you only include ONCE per file(where is needed).

Sign up to request clarification or add additional context in comments.

5 Comments

ok and when do i close the connection then? with the last query in my document?
Someone can correct me if I am wrong, but I think PHP will close the connection automatically at the end of the script exec. But yes you can call close at the end yourself.
@NathanH yes, php will close the connection when the script is done. If its a script that will take a lot of time to execute it might be a good idea to release the connection/s when they are not needed any more tho.
@Nathan H you're right. PHP does close the connection at the end of the script execution.
With the slight exception of persistent connections

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.