16
PHP Package: Database operations using CRUD operations
directory: src/Interfaces/IConnect.php
The default configuration uses the sqlite database.
You can also configure the database of your choice.
Note: Check if the PDO - PHP database extension is supported
/*const DATABASE = "mysql:";
const HOST = "host=localhost;";
const DBNAME = "dbname=name";
const USER = "";
const PASS = "";*/
const DATABASE = "sqlite:".__DIR__."../../database.db";
const HOST = "";
const DBNAME = "";
const USER = null;
const PASS = null;
Method | Description |
---|---|
create(array $data) | Add new entries |
all( ) | List all entries |
find($id) | Find entry by id |
update($id, array $data) | Update or edit existing entries |
delete($id) | Remove existing entries |
execute($sql) | Execute SQL statement |
Somewhere in your project, you may need to use autoload
include __DIR__ ."/vendor/autoload.php";
Let's assume you have a table with the following assignments
users (id,name,age)
Creating the User class
use Tigo\Crud\Abstracts\AbsCrud; //import class
class User extends AbsCrud
{
/**
* Get Table
*/
protected static function getTable()
{
return "users";
}
/**
* Get Primary key
*/
protected static function getPrimaryKey()
{
return "id";
}
}
Now the "User" class can use all the features of the "AbsCrud" class
- EXAMPLE: Add new entries
$data = ['name'=>'Hi','age'=>1];
$user = new User();
$user::create($data);
- EXAMPLE: List all entries
$user = new User();
foreach($user::all() as $item){
echo "ID: ".$item->id."<br>";
echo "Name: ".$item->name."<br>";
echo "Age: ".$item->age."<br>";
echo "----------<br>";
}
- EXAMPLE: Find entry by id
$user = new User();
$id = 1;
foreach($user::find($id) as $item){
echo "ID: ".$item->id."<br>";
echo "Name: ".$item->name."<br>";
echo "Age: ".$item->age."<br>";
echo "----------<br>";
}
- EXAMPLE: Update or edit existing entries
$user = new User();
$id = 1;
$data = ['name'=>'Hiii','age'=>8];
$user::update($id,$data);
- EXAMPLE: Remove existing entries
$user = new User();
$id = 1;
$user::delete($id);
- EXAMPLE: Execute SQL statement
$user = new User();
$sql = "select * from users";
$user::execute($sql);
Download source code: Github
16