Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active July 26, 2020 11:45
Show Gist options
  • Save surferxo3/2a1c06b9b5b373e6f1dbb2f0e1bd9250 to your computer and use it in GitHub Desktop.
Save surferxo3/2a1c06b9b5b373e6f1dbb2f0e1bd9250 to your computer and use it in GitHub Desktop.
NotORM demo of printing sql queries, handling notorm objects, and casting from objects to associative arrays in NotORM framework.
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
// LIBRARIES
require_once 'db/NotORM.php';
// CONSTANTS
const DB_HOST = 'your-host';
const DB_USER = 'your-user';
const DB_PASS = 'your-pass';
const DB_NAME = 'your-dbname';
const DB_TABLE = 'your-table';
const DB_DSN = 'mysql:dbname='. DB_NAME. ';host='. DB_HOST;
// DB STRUCTURE
$structure = new NotORM_Structure_Convention(
$primary = 'ID',
$foreign = '%s_ID',
$table = '%s',
$prefix = '');
$pdo = null;
$db = null;
// HELPER METHODS
function dbConnect() {
global $pdo;
global $db;
global $structure;
$pdo = new PDO(DB_DSN, DB_USER, DB_PASS); // array(PDO::ATTR_PERSISTENT => true) // make persistent connection
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db = new NotORM($pdo, $structure); // new NotORM_Cache_Session()); // enable NotORM caching
}
function dbClose() {
global $pdo;
global $db;
$pdo = null;
$db = null;
}
function debugSql($exit = 0) {
global $db;
$db->debug = function($query, $parameters) use ($exit) {
toScreen($query);
toScreen($parameters, $exit);
};
}
function iteratorToArray($notormResultSet) {
$assocArray = array();
if (!empty($notormResultSet)) {
if ($notormResultSet instanceof NotORM_Result) {
$assocArray = array_map('iterator_to_array', iterator_to_array($notormResultSet));
} else {
$assocArray = iterator_to_array($notormResultSet);
}
}
return $assocArray;
}
function toScreen($data, $exit = 0, $escape = 0) {
echo '<pre>';
if (is_array($data)) {
print_r($data);
} else {
if ($escape) {
echo nl2br($data);
} else {
echo $data;
}
}
echo '</pre>';
ob_flush();
flush();
if ($exit) {
exit;
}
}
// MAIN
dbConnect();
$data = array(
'fld1' => 'val1',
'fld2' => 'val2',
);
# Example
$debugSql(); // use debug before executing the query
$resultInsert = $db->yourtablename()->insert($data);
toScreen(iteratorToArray($resultInsert)); // output associative array to screen
dbClose();
@surferxo3
Copy link
Author

For those who need advance operations using NotORM can buzz me for detailed sample code that I have developed during my practice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment