Skip to content

Instantly share code, notes, and snippets.

@MattSandy
Last active May 26, 2020 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattSandy/195a6fd4a32fa49810ff to your computer and use it in GitHub Desktop.
Save MattSandy/195a6fd4a32fa49810ff to your computer and use it in GitHub Desktop.
Object Oriented Database Connection Quickstart
<?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