Last active
May 26, 2020 17:57
-
-
Save MattSandy/195a6fd4a32fa49810ff to your computer and use it in GitHub Desktop.
Object Oriented Database Connection Quickstart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('DB_NAME', 'zip'); | |
/** MySQL database username */ | |
define('DB_USER', '*****'); | |
/** MySQL database password */ | |
define('DB_PASSWORD', '*****'); | |
/** MySQL hostname */ | |
define('DB_HOST', 'localhost'); | |
$db = new db(); | |
$zip = new zip($db); | |
$zip->all(); | |
class db { | |
public $conn; | |
public function __construct () { | |
try | |
{ | |
$this->conn = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD); | |
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
} | |
catch(PDOException $e) | |
{ | |
echo 'ERROR: ' . $e->getMessage(); | |
} | |
} | |
} | |
class zip { | |
public $db; | |
function __construct($db) { | |
//print_r($db); | |
$this->db = $db; | |
} | |
function all() | |
{ | |
//FETCHING | |
try | |
{ | |
$stmt = $this->db->conn->prepare('SELECT * FROM `cities_extended`'); | |
$stmt->execute(); | |
$result = $stmt->fetchAll(); | |
$count = count($result); | |
if($count) | |
{ | |
echo $count . ' rows returned...'; | |
} | |
else | |
{ | |
echo "No rows returned..."; | |
} | |
} | |
catch(PDOException $e) | |
{ | |
echo 'ERROR: ' . $e->getMessage(); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment