You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Having been introduced to learning Laravel Framework; Over the past yr(s), Coming back to vanilla PHP,
was pretty tough. So i decided to create a much more easier way of communicating with Database, using native PHP PDO:: Driver.
[optional] $options and an array, if no connection data is found
First navigate to [config/database.php] file and add connection configuration or use .env
DB::connection('connName', $options);
Database Disconnect
If you want to connect to already connected database, You first need to disconnect
Takes one param as string
DB::disconnect('connName');
Database Reconnect
same as Database Connection
DB::reconnect('connName', $options);
App Debug Env
The .env file contains a key called APP_DEBUG
It's mandatory to set to false on Production environment
This helps to secure your applicaiton and exit with error 404
instead of displaying entire server errors.
key
Type
Default Value
APP_DEBUG
boolean
true
Database Connection Keys
All available connection keys
The DB_CONNECTION uses only mysql
No other connection type is supported for now.
key
Type
Default Value
driver
string
mysql
host
string
localhost
port
int
3306
database
string
username
string
password
string
charset
string
utf8mb4
collation
string
utf8mb4_unicode_ci
prefix
string
prefix_indexes
bool
false
Usage
All Methods of usage
Without calling the DB::connection() and passing the driver name you want.
It will automatically be using the default connection driver, you've in your setup'
Table
Takes a parameter as string table_name
$db = DB::connection();
$db->table('users');
Insert
Takes one parameter as assoc array column_name => value
It returns an object on success or error
DB::table('users')->insert([
'user_id' => 10000001,
'first_name' => 'Alfred',
'last_name' => 'Pete',
'wallet_bal' => 0.00,
'registered' => strtotime('now'),
]);
-- To see data, you need to save into a variable
Insert Or Ignore
Same as insert() method
It returns an object of created data or false on error
DB::table('posts')->destroy(1);
// Query: delete from `posts` where `id` = ?DB::table('posts')->destroy(10, 'post_id');
// Query: delete from `posts` where `post_id` = ?
Increment
Takes three parameter
Only the first param is required
param
Data types
column required
string
count or []
int | array
param
array
1 By default if the the second param not passed, this will increment by 1
Same as first() method but exit with error code 404, if data not found
DB::table('users')->firstOrFail();
Count
DB::table('users')->count();
Paginate
Takes param as int$per_page
By default if no param is given, then it displays 10 per page
$users = DB::table('users')
->paginate(40);
$users // this will return the data objects$users->links() // this will return the paginations links view$users->showing() // Display items of total results
When the view is either loading| | onloading | cursor | bootstrap
This can automatically fetched data without page load
You need to give your DOM-element data-pagination-content and data-pagination-append
$users = DB::table('users')->paginate(20);
<divdata-pagination-content><divclass="wallet-container" data-pagination-append><?php foreach($users as $user) {?><!-- Content to be loaded structure --><?php }?></div></div>
or
<divdata-pagination-contentdata-pagination-append><!-- Content to be loaded structure --></div><!-- pagination links --><div><?= $users->links([
'no_content' => 'All users have been loaded.'
]); ?></div>
Similar to Laravel DB Migration Just to make database table creation more easier
method name
Returns
create()
Create table schema
run()
Begin migration
drop()
Drop migration tables
useTamedevelopers\Database\Migrations\Migration;
Create Table Schema
Takes param as string $table
[optional] Second parameter stringjobs|sessions If passed will create a dummy jobs|sessions table schema
It's helper class can be called, using -- migration()
Migration::create('users');
Migration::create('users_wallet');
Migration::create('tb_jobs', 'jobs');
Migration::create('tb_sessions', 'sessions');
// migration()->create('users');// Table `2023_04_19_1681860618_user` has been created successfully// Table `2023_04_19_1681860618_user_wallet` has been created successfully// Table `2023_04_19_1681860618_tb_jobs` has been created successfully// Table `2023_04_19_1681860618_tb_sessions` has been created successfully
This will execute and run migrations using files located at [root/database/migrations]
Migration::run();
or
migration()->run();
// Migration runned successfully on `2023_04_19_1681860618_user` // Migration runned successfully on `2023_04_19_1681860618_user_wallet`
Drop Migration
Read more...
Be careful as this will execute and drop all files table located in the migration
[optional param] bool to force delete of tables
Migration::drop();
or
migration()->drop(true);
Drop Table
Read more...
Takes one param as string $table_name
useTamedevelopers\Database\Migrations\Schema;
Schema::dropTable('table_name');
or
schema()->dropTable('table_name');
Drop Column
Read more...
To Drop Column takes two param
This will drop the column available
useTamedevelopers\Database\Migrations\Schema;
Schema::dropColumn('table_name', 'column_name');
or
schema()->dropColumn('table_name', 'column_name');
Get Database Config
$db->getConfig()
Get Database Connection
It's helper class can be called, using -- db_connection()
$db->dbConnection()
Get Database Name
$db->getDatabaseName()
Get Database PDO
$db->getPDO()
Get Database TablePrefix
$db->getTablePrefix()
Database Import
You can use this class to import .sql into a database programatically
Take two param as [$path|$connection]
Mandatory $path as string of path to .sql file
[optional] $connection define the connection of database you want to run
useTamedevelopers\Database\DBImport;
$database = newDBImport('path_to/orm.sql', 'connName');
// new DBImport(base_path('path_to/orm.sql'))// run the method$status = $database->run();
// - Status code// ->status == 404 (Failed to read file or File does'nt exists// ->status == 400 (Query to database error// ->status == 200 (Success importing to database
Update Env Variable
You can use this class to import .sql into a database programatically
Params
Description
key
ENV key
value
ENV value
allow_quote
true | false - Default is true (Allow quotes within value)
allow_space
true | false - Default is false (Allow space between key and value)
You can as well extends the DB Model class directly from other class
useTamedevelopers\Database\Model;
class Post extends Model{
// define your custom model table nameprotected$table = 'posts';
// -- You now have access to the DB public instancespublicfunctiongetPost(){
return$this->select(['images', 'title', 'description'])->get();
}
}
Helpers Functions
function name
Description
db()
Return instance of new DB($options) class
db_connection()
Same as $db->dbConnection()
config_pagination()
Same as $db->configPagination() or AutoLoader::configPagination
autoloader_start()
Same as AutoLoader::start()
env_update()
Same as Env::updateENV method
app_manager()
Return instance of (new AppManager) class
import()
Return instance of (new DBImport)->import() method