0

Okay this might be an obvious question, but as soon as i call MySQL with PHP (whhich means i log in) and then close the PHP tag, (shown below) Do I have to call the database again later?

$mysqli = new mysqli("host", "username", "pw", "dbname");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}                      
$res = $mysqli->query("SELECT EmbedURL FROM Videos ORDER BY RAND() LIMIT 8"); 

etc... And then I need to call it again later in the script to fetch something else fromt he database. Do i have to log into the database again?

Thank you!

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
  • As long as you don't close the connection then you can use the `$mysqli` further down the page yes. – Epodax Oct 05 '16 at 09:27
  • when you construct a `mysqli` object, you are not just "logging in" to the database, you are establishing a database connection. technically, it should work in a second php tag on the same page unless you explicitly closed the connection before reaching that point. – Timothy Groote Oct 05 '16 at 09:27
  • Thx a lot both of you! –  Oct 05 '16 at 09:46

1 Answers1

0

The database connection will stay open if you do not close it manually. The only possible cause I can imagine that you could loose the connection is the connection timed out or was closed by the databse because you have to many active connections. It looks like the database variable is nested deeply in your code. You will also loose the reference of the connection if you close the current code block (}).

Here is a post about MySQL connection pooling which could be insteresting for your problem: Connection pooling in PHP

Fjolnir Dvorak
  • 316
  • 3
  • 13