An easy to use class for Database queries in 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);See Below for usage.
Database::connect('database','password','username','host');Note the reverse parameters. We do this because of the ommitable variables.
If you want to use an existing PDO object to connect:
$db = new PDO; # Use Connection details
Database::setPdo($db); # Pass the objectIf you want to use this database's PDO object to pass to other objects:
$db = Database::getPdo(); # Returns PDO object after connect() is called$query = Database::query("SELECT * FROM table WHERE id = ?", [$_GET['id']]);This is a query with bind parameters. First argument is the statement, second argument is an array of parameters (optional)
Note: We passed the query into a variable for later re-use.
This is regular returned object. You still need to apply htmlspecialchars yourself.
$table = Database::fetch_object($query);This is safe returned object. htmlspecialchars is applied to all the objects's properties.
$table = Database::fetch_safe_object($query);Database::num_rows($query); # Equivalent of $pdo->rowCount();# Loop Objects
while($entry = Database::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);
echo $entry->name;
# Loop Objects Using Foreach instead with Fetchall
foreach(Database::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);
echo $entry[0]->name;via Composer:
{
"require": {
"modularr/database": "1.*"
}
}Then run:
composer update
Or install like so:
composer require modularr/database
make sure you have:
require 'vendor/autoload.php';Manual:
- Download Release Or copy file manually
- Include Database.php (found under src/)
- Check out the example