PHP code example of initorm / database

1. Go to this page and download the library: Download initorm/database library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

initorm / database example snippets


use \InitORM\Database\Facade\DB;

// Connection
DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
]);

use \InitORM\Database\Facade\DB;
$data = [
    'title'     => 'Post Title',
    'content'   => 'Post Content',
];

$isInsert = DB::create('post', $data);

/**
* This executes the following query.
* 
* INSERT INTO post 
* (title, content) 
* VALUES 
* ("Post Title", "Post Content");
*/
if($isInsert){
    // Success
} else {
    foreach (DB::getErrors() as $errMsg) {
        echo $errMsg;
    }
}

use \InitORM\Database\Facade\DB;

$data = [
    [
        'title'     => 'Post Title 1',
        'content'   => 'Post Content 1',
        'author'    => 5
    ],
    [
        'title'     => 'Post Title 2',
        'content'   => 'Post Content 2'
    ],
];

$isInsert = DB::createBatch('post', $data);

/**
* This executes the following query.
* 
* INSERT INTO post 
* (title, content, author) 
* VALUES 
* ("Post Title 1", "Post Content 1", 5),
* ("Post Title 2", "Post Content 2", NULL);
*/

if($isInsert){
    // Success
}

use \InitORM\Database\Facade\DB;


/**
* This executes the following query.
* 
* SELECT user.name AS author_name, post.id, post.title 
* FROM post, user 
* WHERE user.id = post.author AND post.status = 1
* ORDER BY post ASC, post.created_at DESC
* LIMIT 20, 10
*/

$res = DB::select('user.name as author_name', 'post.id', 'post.title')
    ->from('post')
    ->selfJoin('user', 'user.id=post.author')
    ->where('post.status', 1)
    ->orderBy('post.id', 'ASC')
    ->orderBy('post.created_at', 'DESC')
    ->offset(20)->limit(10)
    ->read();
    
if($res->numRows() > 0){
    $results = $res->asAssoc()
                    ->rows();
    foreach ($results as $row) {
        echo $row['title'] . ' by ' . $row['author_name'] . '<br />';
    }
}

use \InitORM\Database\Facade\DB;
$data = [
    'title'     => 'New Title',
    'content'   => 'New Content',
];

$isUpdate = DB::where('id', 13)
                ->update('post', $data);
    
/**
* This executes the following query.
* 
* UPDATE post 
* SET title = "New Title", content = "New Content"
* WHERE id = 13
*/
if ($isUpdate) {
    // Success
}

use \InitORM\Database\Facade\DB;
$data = [
    [
        'id'        => 5,
        'title'     => 'New Title #5',
        'content'   => 'New Content #5',
    ],
    [
        'id'        => 10,
        'title'     => 'New Title #10',
    ]
];

$isUpdate = DB::where('status', '!=', 0)
                ->updateBatch('id', 'post', $data);
    
/**
* This executes the following query.
* 
* UPDATE post SET 
* 	title = CASE 
* 		WHEN id = 5 THEN 'New Title #5' 
* 		WHEN id = 10 THEN 'New Title #10' 
* 		ELSE title END, 
* 	content = CASE 
* 		WHEN id = 5 THEN 'New Content #5'
* 		ELSE content END 
* WHERE status != 0 AND id IN (5, 10)
*/
if ($isUpdate) {
    // Success
}

use \InitORM\Database\Facade\DB;

$isDelete = DB::where('id', 13)
                ->delete('post');
    
/**
* This executes the following query.
* 
* DELETE FROM post WHERE id = 13
*/
if ($isUpdate) {
    // Success
}

use \InitORM\Database\Facade\DB;

$res = DB::query("SELECT id, title FROM post WHERE user_id = :id", [
    ':id'   => 5
]);

if ($res->numRows() > 0) {
    $result = $res->asObject()
                    ->row();
    
    echo $result->title;
}

use \InitORM\Database\Facade\DB;

$res = DB::select(DB::raw("CONCAT(name, ' ', surname) AS fullname"))
        ->where(DB::raw("title = '' AND (status = 1 OR status = 0)"))
        ->limit(5)
        ->read('users');
        
/**
 * SELECT CONCAT(name, ' ', surname) AS fullname 
 * FROM users 
 * WHERE title = '' AND (status = 1 OR status = 0)
 * LIMIT 5
 */
$results = $res->asAssoc()
                ->rows();
foreach ($results as $row) {
    echo $row['fullname'];
}

use \InitORM\Database\Facade\DB;

DB::connect([
    'dsn'       => 'mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
]);

use \InitORM\Database\Facade\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'log'       => __DIR__ '/logs/db.log', // string, callable or object
]);

use \InitORM\Database\Facade\DB;

class Logger {
    
    public function critical(string $msg)
    {
        $path = __DIR__ . '/log.log';
        file_put_contents($path, $msg, FILE_APPEND);
    }

}

$logger = new Logger();

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'log'       => $logger, // or [$logger, 'critical']
]);

use \InitORM\Database\Facade\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'log'       => function (string $msg) {
        $path = __DIR__ . '/log.log';
        file_put_contents($path, $msg, FILE_APPEND);
    },
]);

use \InitORM\Database\Facade\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',
    
    'debug'     => true, // boolean
]);

use InitPHP\Database\Facade\DB;

DB::enableQueryLog();

DB::table('users')->where('name', 'John')->read();

var_dump(DB::getQueryLogs());

/**
 * The output of the above example looks like this;
 * [
 *      [
 *          'query' => 'SELECT * FROM users WHERE name = :name',
 *          'time'  => '0.00064',
 *          'args'  => [
 *              ':name'     => 'John',
 *          ]
 *      ]
 * ]
 * 
 */