PHP code example of webx / db

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

    

webx / db example snippets


    use WebX\Db\Db;
    use WebX\Db\Impl\DbImpl;

    $db = new DbImpl([
        "user" => "mysqlUser",
        "password" => "mysqlPassword",
        "database" => "mysqlDatabase"
    ]);

    //or

    $db = new DbImpl($mysqli); //Instance of mysqli


    $person = ["first"=>"Alex", "last"=>"Morris","email"=>"[email protected]"];
    $db->execute("INSERT INTO people (first,last,email,phone) VALUES(:first,:last,:email,:phone)", $person);
    //SQL: INSERT INTO people (first,last,email,phone) VALUES('Alex','Morris','am@domain',NULL);

    $id = $db->insertId();          //The value of the autogenerated primary key.

    foreach($db->allRows("SELECT * FROM table") as $row) {
        echo($row->string('first'));
        echo($row->string('last'));
    }

    $person = [...];
    try {
        $db->execute("INSERT INTO people (first,last,email) VALUES(:first,:last,:email)", $person);
        echo("Person registered");
    } catch(DbKeyException $e) {
        if($e->key()==='emailKey') { // Name of the defined unique key in MySQL
            echo("The {$person->string('email')} is already registered";
        } else {
            echo("Some other key violation occured.");
        }
    }




    $db->startTx();
    $db->execute("INSERT INTO table (col) VALUES('1')");

        $db->startTx();
        $db->execute("INSERT INTO table (col) VALUES('2')"); // Will not be commited
        $db->rollbackTx();

        $db->startTx();
        $db->execute("INSERT INTO table (col) VALUES('3')");
        $db->commitTx();

    $db->commitTx();


    $db->executeInTx(function($db) { // The db instance must be passed as the only argument to closure.
        $db->execute("INSERT INTO table (col) VALUES('1')");
        $db->execute("INSERT INTO table (col) VALUES('2')");

        if(true) { //Now the transaction will be rolled back
            throw new \Exception("An error occured");
        }
    });