PHP code example of basephp / database

1. Go to this page and download the library: Download basephp/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/ */

    

basephp / database example snippets


use \Base\Support\Facades\DB;

// get a single user from the database
$user = DB::table('users')->where('id',912864)->first();

// get all users in the database, order the results
$users = DB::table('users')->order('id ASC')->get();

// get all users that have gmail email address (writing custom SQL)
$users = DB::table('users')->where('email LIKE "%gmail.com" ')->get();

// count how many users are enabled
$enabledUsers = DB::table('users')->where(['status'=>'enabled'])->count();

// get most recent 10 enabled users
$users = DB::table('users')
            ->select(['id','name'])
            ->where(['status'=>'enabled'])
            ->limit(10)
            ->order('id DESC')
            ->get();

// get all the cities that have over 1,000,000 population
$cities = DB::table('postal_codes')
            ->group('city')
            ->having('population > 1000000')
            ->get();

// get the average price of all ebooks from the products table
$avgPrice = DB::table('products')->where('category','ebooks')->avg('price');

// change user's name
DB::table('users')
    ->where('id',912864)
    ->update([
        'name' => 'John Smith'
    ]);

// increase this users "page view" count
DB::table('users')->where('id',9983287)->increment('page_view',1);

// add a new user to the table, and return the new ID
$newUserId =  DB::table('users')
                ->insert([
                    'name' => 'John Smith',
                    'email' => '[email protected]'
                ]);

// delete a user by id
DB::table('users')
    ->where('id',912864)
    ->delete();

// delete all users with deleted = 1
DB::table('users')
    ->where(['deleted' => 1])
    ->delete();

// Writing a RAW SQL query to get 10 products from the database.
$products = DB::query("SELECT * FROM products WHERE status = 'enabled' LIMIT 10");
foreach($products as $product)
{
    // display products here
}

// get a single products
$product = DB::query("SELECT * FROM products WHERE id = '$productId'")->first();

// writing an update query
DB::query("UPDATE products SET price = 61.41 WHERE id = '$id' ");

// writing raw queries (without the query builder)
$newUserId = DB::query("INSERT INTO users WHERE name = 'John Smith', email = '[email protected]' ");