I have PHP file where I have defined the server access variables as well as the mysql_connect
and mysql_select_db
, as this functions are regularly
If your page will not work without the DB connection, then require_once would be the only correct option (since you don't want to load these settings twice, loading them once should suffice). Include will try to load your page even if the settings file is not available.
require() is better for you. Because with require file includes before script compilation. inluce() using in dinamical including.
For the database connection variables, use of require_once() function will be preferable. If the connection fails for any reason you can show the failure message.
Include The include() statement includes and evaluates the specified file.
Include Once The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
Require require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page.
Require Once The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
<?php
include('db.php');
echo "<br>"."Included"."<br>";
include_once('db.php');
echo "<br>"."Again included"."<br>";
?>
In the Above Code, I have included a file using include statement at the top, the file get included.
Next I have used include_once to include the same file, But as the file was already included above, it will not be included again here.
Connected -----This is from db.php File
Included
Again included
==========================
include_once('db.php');
echo "<br>"."Again included"."<br>";
include('db.php');
echo "<br>"."Included"."<br>";
?>
In the above code, I have used include_once at the top, so the file is included But in the next code I have again used include_once for the same file, then again the file will get included and the output will be
Again included
Connected
Included
Connected
You should use include_once() if you're including it more than once on a page.