Jump to: navigation, search

PHP MySQL PDO Connect with function

From w3cyberlearnings

Contents

PHP PDO Connection with custom function

Create a custom function for PDO connect.

Syntax PDO connect function

// create function
function pdo_connect() {
	try {
		$dns = 'mysql:host=localhost;dbname=w3cyberlearning';
		$user = 'user2000';
		$pass = 'password2000';
		$db = new PDO($dns, $user, $pass);
		return $db;
	} catch (PDOException $e) {
		echo $e->getMessage();
		return false;
	}
}

// connect

$dbh = pdo_connect();


Example 1: Use function

<?php

function pdo_connect() {
	try {
		$dns = 'mysql:host=localhost;dbname=w3cyberlearning';
		$user = 'user2000';
		$pass = 'password2000';
		$db = new PDO($dns, $user, $pass);
		return $db;
	} catch (PDOException $e) {
		echo $e->getMessage();
		return false;
	}
}

// make connection uses function
$result = pdo_connect();

if ($result) {
	echo 'connected';
}
?>


Related Links


Navigation
Web
SQL
MISC
References