PHP Code Snippets

Simple MySQL Database Connection

Defining the variables and creating the function to connect to the DB:

define('USER', 'DB_User_Name'); 	// Database User Name
define('PASSWORD', 'DB_Password'); 	// Password for the Database User
define('HOST', 'DB_Host'); 		// Host of the Database, eg localhost
define('DATABASE', 'DB_Name'); 		// Database Name
try {
	$connection = new PDO("mysql:host=".HOST.";dbname=".DATABASE, USER, PASSWORD); // Attempts to connect to the database with defined variables.
} catch (PDOException $e) {
	exit("Error: " . $e->getMessage()); // Provides an error message if connection is unsuccessful.
}

Example to call the database connection and execute a query:

$query = $connection->prepare("SELECT * FROM accounts WHERE username=:username");
$query->bindParam("username", $username, PDO::PARAM_STR);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);

And finally, to close out the connection:

$connection = null;