Skip to content

Commit

Permalink
Update 2.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
modbot committed Apr 8, 2020
1 parent bef7db2 commit 4818433
Show file tree
Hide file tree
Showing 5 changed files with 225 additions and 77 deletions.
127 changes: 84 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,101 @@
An easy to use class for Database queries in PHP.

- [API](#api)
- [Connections](#connections)
- [Examples](#data-examples)
- [Install](#installation)

## API
```php
Database::connect($db='test',$pass='',$user='root',$host='localhost',$type='mysql');
Database::getPdo();
Database::setPdo($db);
Database::query($query, $params = array());
Database::fetchAll($query);
Database::fetchAll_safe($query);
Database::fetch_assoc($query);
Database::fetch_safe_assoc($query);
Database::fetch_object($query);
Database::fetch_safe_object($query);
Database::num_rows($query);
DB::connect($db='test',$pass='',$user='root',$host='localhost',$type='mysql');
DB::getPdo();
DB::setPdo($db);
DB::quote();
DB::query($query, $params = array());
DB::fetchAll($query);
DB::fetchAll_safe($query);
DB::fetch_assoc($query);
DB::fetch_safe_assoc($query);
DB::fetch_object($query);
DB::fetch_safe_object($query);
DB::num_rows($query);
```

See Below for usage.

### Connecting
## Connections

Our class lets you connect to PDO whichever way you choose, This maximizes flexibility by letting you simply give us your already existing object, or by using our class as your primary Database package and asking for the PDO object if you need to pass it to other libraries.


### Connection Syntax

We let you connect using multiple syntax to make it easy to use, available both in the `__construct()` as well as `connect()`

You can either use an associative array or the default which uses reverse order to let you define the most important values first, and lets you default irrelevant values such as host or type to it's defaults ('mysql' and 'localhost')

### Via Instantiation

```php
$db = new Database($db='test',$pass='',$user='root',$host='localhost',$type='mysql'); # Default Syntax
$db = new Database(['host'=>$host,'dbname'=>$database,'user'=>$username,'pass'=>$password]); # Alternative Syntax
```

### Via Method

```php
$db->connect(DB,PASS,USER,HOST); # Establish a Connection With PDO
```

### Via Existing PDO Object

```php
$db->setPdo($pdo); # Assign PDO Connection to the Database Class
```

## Usage and Use Case

A facade is optional but has all the same functionality of the main class.

# Regular Use Case

```php
Database::connect('database','password','username','host');
$db = new Database(DB,PASS,USER,HOST); # Establish a Connection
$query = $db->query("SELECT * FROM table");
while($item = $db->fetch_object($query))
{
echo'#'.htmlspecialchars($item->id).': '.htmlspecialchars($item->name).'<br>';
}
```

Note the reverse parameters. We do this because of the ommitable variables.
# Facades Use Case

### Create Facade from PDO Object

### PDO Objects
```php
$db = new Database(DB,PASS,USER,HOST); # Establish a Connection
DB::Facade($db); # Initiate Database object Facade
```

If you want to use an existing PDO object to connect:
### Connect Via Facade

```php
$db = new PDO; # Use Connection details
Database::setPdo($db); # Pass the object
DB::connect('database','pass','user','host');
```

If you want to use this database's PDO object to pass to other objects:
### Use Case

```php
$db = Database::getPdo(); # Returns PDO object after connect() is called
$query = DB::query("SELECT * FROM table");
while($item = DB::fetch_object($query))
{
echo'#'.htmlspecialchars($item->id).': '.htmlspecialchars($item->name).'<br>';
}
```

### Query
```php
$query = Database::query("SELECT * FROM table WHERE id = ?", [$_GET['id']]);
$query = DB::query("SELECT * FROM table WHERE id = ?", [$_GET['id']]);
```

This is a query with bind parameters.
Expand All @@ -58,67 +108,58 @@ Note: We passed the query into a variable for later re-use.
### Fetch and **Safe Fetch**
This is regular returned object. You still need to apply htmlspecialchars yourself.
```php
$table = Database::fetch_object($query);
$table = DB::fetch_object($query);
```

This is safe returned object. htmlspecialchars is applied to all the objects's properties.
```php
$table = Database::fetch_safe_object($query);
$table = DB::fetch_safe_object($query);
```

### Num Rows
```php
Database::num_rows($query); # Equivalent of $pdo->rowCount();
DB::num_rows($query); # Equivalent of $pdo->rowCount();
```

### Data Examples
```php
# Loop Objects
while($entry = Database::fetch_safe_object($query))
while($entry = DB::fetch_safe_object($query))
{
# Because of fetch_safe_object we don't need to apply htmlspecialchars
echo '<a href="page?id='.$entry->id.'">'.$entry->name.'</a><br />';
}
# Single Object
$entry = Database::fetch_safe_object($query);
$entry = DB::fetch_safe_object($query);
echo $entry->name;

# Loop Objects Using Foreach instead with Fetchall
foreach(Database::fetchAll_safe($query) as $entry)
foreach(DB::fetchAll_safe($query) as $entry)
{
# Because of fetchAll_safe we don't need to apply htmlspecialchars
echo '<a href="page?id='.$entry->id.'">'.$entry->name.'</a><br />';
}
# Single Object
$entry = Database::fetchAll_safe($query);
$entry = DB::fetchAll_safe($query);
echo $entry[0]->name;
```

## Installation

via Composer:

composer require modularr/database

Or install like so:
```json
{
"require": {
"modularr/database": "1.*"
"modularr/database": "2.*"
}
}
```
Then run:

composer update

Or install like so:

composer require modularr/database

make sure you have:
```php
require 'vendor/autoload.php';
```

Manual:

1. Download [Release](https://github.com/Modularr/Database/releases) Or copy file manually
2. Include **Database.php** (found under **src/**)
3. Check out the example
2. Include **Main.php** found under **src/** (this includes both **Database.php** and **Facade.php**)
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
"keywords": ["modularr","database","mysql","pdo"],
"license": "UNLICENSE",
"autoload": {
"classmap": ["src/", "src/Database.php"]
"classmap": ["src/", "src/Main.php"]
}
}
104 changes: 71 additions & 33 deletions src/Database.php
Original file line number Diff line number Diff line change
@@ -1,81 +1,119 @@
<?php
class Database
{
public static $pdo,$query,$res;
public static function connect($db='test',$pass='',$user='root',$host='localhost',$type='mysql')
public $pdo;
private $query,$res;
private $host = 'localhost';
private $type = 'mysql';
private $dbname = 'test';
private $user = 'root';
private $pass = '';
public function __construct($data=null,$pass=null,$user=null,$host=null,$type=null)
{
try {
self::$pdo = new PDO("$type:host=$host;dbname=$db", $user, $pass);
self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
if( isset($data) || isset($pass) || isset($user) || isset($host) || isset($type) ) {
if(is_array($data)) {
if(isset($data['dbname'])) { $this->dbname = $data['dbname']; }
if(isset($data['pass'])) { $this->pass = $data['pass']; }
if(isset($data['user'])) { $this->user = $data['user']; }
if(isset($data['host'])) { $this->host = $data['host']; }
if(isset($data['type'])) { $this->type = $data['type']; }
} else {
if(isset($data)) { $this->dbname = $data; }
if(isset($pass)) { $this->pass = $pass; }
if(isset($user)) { $this->user = $user; }
if(isset($host)) { $this->host = $host; }
if(isset($type)) { $this->type = $type; }
}
$this->connect();
}
}
public function connect($data=null,$pass=null,$user=null,$host=null,$type=null)
{
if( isset($data) || isset($pass) || isset($user) || isset($host) || isset($type) ) {
if(isset($data)) { $this->dbname = $data; }
if(isset($pass)) { $this->pass = $pass; }
if(isset($user)) { $this->user = $user; }
if(isset($host)) { $this->host = $host; }
if(isset($type)) { $this->type = $type; }
}
if(isset($this->type) || isset($this->host) || isset($this->$user) || isset($this->pass) || isset($this->dbname)) {
try {
$this->pdo = new PDO($this->type.':host='.$this->host.';dbname='.$this->dbname, $this->user, $this->pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
}
public function setPdo($obj)
{
$this->pdo = $obj;
}
public static function setPdo($obj)
public function getPdo()
{
self::$pdo = $obj;
return $this->pdo;
}
public static function getPdo()
public function quote($string)
{
return self::$pdo;
return $this->pdo->quote($string);
}
public static function query($query, $params = array())
public function query($query, $params = array())
{
self::$query = self::$pdo->prepare($query);
$this->query = $this->pdo->prepare($query);
if(!empty($params)) {
self::$query->execute($params);
$this->query->execute($params);
} else {
self::$query->execute();
$this->query->execute();
}
return self::$query;

return $this->query;
}
public static function fetch_assoc($query)
public function fetch_assoc($query)
{
return $query->fetch(PDO::FETCH_ASSOC);
}
public static function fetch_safe_assoc($query)
public function fetch_safe_assoc($query)
{
$res = self::walk_recursive($query->fetch(PDO::FETCH_ASSOC), 'htmlspecialchars');
$res = $this->walk_recursive($query->fetch(PDO::FETCH_ASSOC), 'htmlspecialchars');
return $res;
}
public static function fetch_object($query)
public function fetch_object($query)
{
return $query->fetch(PDO::FETCH_OBJ);
}
public static function fetch_safe_object($query)
public function fetch_safe_object($query)
{
$res = self::walk_recursive($query->fetch(PDO::FETCH_OBJ), 'htmlspecialchars');
$res = $this->walk_recursive($query->fetch(PDO::FETCH_OBJ), 'htmlspecialchars');
return $res;
}
public static function fetchAll($query)
public function fetchAll($query)
{
return $query->fetchAll(PDO::FETCH_OBJ);
}
public static function fetchAll_safe($query)
public function fetchAll_safe($query)
{
$res = self::walk_recursive($query->fetchAll(PDO::FETCH_OBJ), 'htmlspecialchars');
$res = $this->walk_recursive($query->fetchAll(PDO::FETCH_OBJ), 'htmlspecialchars');
return $res;
}
public static function num_rows($query)
public function num_rows($query)
{
return $query->rowCount();
}
public static function insert_id()
public function insert_id()
{
$id = self::$pdo->lastInsertId();
$id = $this->pdo->lastInsertId();
return $id;
}
public static function walk_recursive($obj, $closure)

public function walk_recursive($obj, $closure)
{
if ( is_object($obj) )
{
$newObj = new stdClass();
foreach ($obj as $property => $value)
{
$newProperty = $closure($property);
$newValue = self::walk_recursive($value, $closure);
$newValue = $this->walk_recursive($value, $closure);
$newObj->$newProperty = $newValue;
}
return $newObj;
Expand All @@ -86,7 +124,7 @@ public static function walk_recursive($obj, $closure)
foreach ($obj as $key => $value)
{
$key = $closure($key);
$newArray[$key] = self::walk_recursive($value, $closure);
$newArray[$key] = $this->walk_recursive($value, $closure);
}
return $newArray;
}
Expand Down
Loading

0 comments on commit 4818433

Please sign in to comment.