I think the most secure way of retrieving the data from a database it the 1 that requests the db access details from an external file and passes them (ideally as a file)to a function dealing with establishing the connection using those details and returning the connection to a caller.

To implement above scenario, we are going to create 3 simple files: db_details.inc.php, connect_function.inc.php and example.php - which displays some data.

db_details.inc.php holds 4 variables: $host, $username, $password and $database

$host = "localhost";
$user = "--username--";
$passwd = "--password--";
$database = "--database name--";

example.php will pass those details as a file to connect_function.inc.php which will use them in order to gain an access to a database.


$cxn = Connect_to_db("db_details.inc.php");

$sql = "SELECT * FROM Client
WHERE ClientID=1";

$result = mysqli_query($cxn,$sql)
or die("Couldn't execute query - displaying client details");

Once the connection is retued to example.php, we may execute any SQL queries no matter whether we are going to display, update or insert new records.


function Connect_to_db($filename)

$connection = mysqli_connect($host,$user,$passwd)
or die ("Couldn't connect to server.");

$db = mysqli_select_db($connection,$database)
or die ("Couldn't select database.");

return $connection;