JohnPaulDesign
11/18/2016 - 10:50 AM

Connect to a database

Connect to a database

<?php
// A secure trick for connecting to a database is to convert the credentials into uppercase constants through an array
// This code should sit in a db.php file in an includes or conf folder

$db['db_host'] = "localhost";
$db['db_user'] = "root";
$db['db_pass'] = "...";
$db['db_name'] = "...";

foreach ($db as $key => $value) {
	define(strtoupper($key), $value);
}

//the connection variable can be used to refer to the database in other scripts, as long as this script is included on the page
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Display if connection was unsuccessfull
if(!$connection) {
	echo "Could not connect to database";
}

?>