PHP code example of phossa2 / db

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

    

phossa2 / db example snippets


    use Phossa2\Db\Driver\Pdo\Driver as Pdo_Driver;

    $db = new Pdo_Driver([
        'dsn' => 'mysql:dbname=test;host=127.0.0.1;charset=utf8'
    ]);

    // simple delete
    if ($db->query("DELETE FROM test WHERE id < 10")) {
        echo sprintf("%d records deleted", $db->affectedRows()) . \PHP_EOL;
    } else {
        echo $db->getError() . \PHP_EOL;
    }

    // with parameters
    if ($db->query("INSERT INTO test (val) VALUES (?)", [ 100 ])) {
        echo sprintf("last id is %d", $db->lastInsertId()) . \PHP_EOL;
    } else {
        echo $db->getError() . \PHP_EOL;
    }
    

    // simple select
    if ($db->query("SELECT * FROM test WHERE id < 10")) {
        $rows = $db->getResult()->fetchAll();
    } else {
        echo $db->getError() . \PHP_EOL;
    }

    // fetch first 5 rows
    if ($db->query("SELECT * FROM test WHERE id > ? LIMIT ?", [10, 20])) {
        $rows = $db->getResult()->fetchRow(5);
    }

    // fetch first field
    if ($db->query("SELECT id, name FROM test WHERE id < :id", ['id' => 10])) {
        $cols = $db->getResult()->fetchCol('id');
    }
    

  // PREPARE using prepare()
  if ($db->prepare("SELECT * FROM test WHERE id < :id")) {
      $stmt = $db->getStatement();
      if ($stmt->execute(['id' => 10])) {
          $rows = $stmt->getResult()->fetchAll();
      }
  } else {
      echo $db->getError() . \PHP_EOL;
  }
  

  if ($db->query('SELECT * FROM test')) {
      // SELECT
      if ($db->getResult()->isSelect()) {
          // get fields count
          $fieldCount = $db->getResult()->fieldCount();
          // row count
          $rowCount = $db->getResult()->rowCount();

      // DDL
      } else {
          $affectedRows = $db->getResult()->affectedRows();
      }
  }
  

use Phossa2\Db\Driver\Mysqli\Driver as Mysqli_Driver;

$db = new Mysqli_Driver([
    'db' => 'mysql',
    'host' => '127.0.0.1',
    'charset' => 'utf8'
]);

// simple delete
if ($db->query("DELETE FROM test WHERE id < ?", [10])) {
    echo sprintf("%d records deleted", $db->affectedRows()) . \PHP_EOL;
} else {
    echo $db->getError() . \PHP_EOL;
}

// init driver
$db = new Phossa2\Db\Driver\Pdo\Driver($conf);

// enable profiling
$db->enableProfiling();

// execute a DELETE
$db->query("DELETE FROM test WHERE test_id > 10");

// get sql
$sql = $db->getProfiler()->getSql();
$time = $db->getProfiler()->getExecutionTime();

if ($db->query('SELECT * FROM test')) {
    // normally is $db->getResult()->fetchAll()
    $rows = $db->fetchAll();
}