Not a member of Pastebin yet?
                        Sign Up,
                        it unlocks many cool features!                    
                - <?php
 - // declare a config variable that can be accessed by including this file
 - $config = require("config.php");
 - class Connection {
 - // establish connection details from config file
 - function __construct() {
 - $config = require("config.php");
 - $this->db_host = $config["masterDB"]["host"];
 - $this->db_user = $config["masterDB"]["user"];
 - $this->db_pass = $config["masterDB"]["password"];
 - $this->db_name = $config["masterDB"]["name"];
 - }
 - // make the connection
 - public function connect() {
 - $this->connect_db = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
 - if (mysqli_connect_errno()) {
 - die("Connection failed: %s\n".mysqli_connect_error());
 - exit();
 - }
 - if (!$this->connect_db->set_charset("utf8")) {
 - die("Could not set character set to UTF8: %s\n".$this->connect_db->error);
 - exit();
 - }
 - return true;
 - }
 - // return the current connection
 - public function get_connection() {
 - return $this->connect_db;
 - }
 - }
 - /*
 - class container for art request actions
 - */
 - class RequestTemplate {
 - /**
 - * @var object Mysqli instance used for database operations
 - */
 - var $mysqli = null;
 - /**
 - * @var integer ID of user performing operations
 - */
 - var $currentUSER = null;
 - /**
 - * @var integer ID of current request being worked with
 - */
 - var $currentID = null;
 - /**
 - * @var boolean If false will not automatically commit changes to database (requires external mysqli be declared)
 - */
 - var $autoCommit = true;
 - /**
 - * @var boolean If true will throw an exception upon error rather than the default behavior
 - */
 - var $useException = false;
 - /**
 - * @var array An array of field names and their datatypes fpr constructing insert & update statements
 - */
 - protected $fieldTypes = array();
 - /**
 - * @var string The current table to perform insert & update operations on
 - */
 - private $currentTable = null;
 - /**
 - * @var array A white-list of tables eligible for insert & update operations
 - */
 - private $tablesWhitelist = array();
 - /**
 - * @var array A white-list of functions that can be used in insert & update operations
 - */
 - var $myslqFuncWhiteList = array(null, "null", "NULL", "NOW()");
 - /**
 - * Class constructor
 - *
 - * @param mixed[false|object] $mysqli An existing mysqli instance or false to initialize one
 - * @param mixed[boolean|integer] $exists The ID of the request currently being operated on, or false if unknown (or a new request)
 - * @param boolean $autocommit If false will not automatically commit mysql transactions (which requires an external instance of mysqli)
 - */
 - function __construct($mysqli = false, $exists = false, $autocommit = true) {
 - if ($mysqli == false) {
 - if ($autocommit == false) {
 - $this->handleErr("autocommit can not be used without an existing mysqli connection");
 - }
 - $this->checkDBConn();
 - } else {
 - $this->mysqli = $mysqli;
 - }
 - if ($exists != false && is_int( intval($exists) )) {
 - $this->currentID = $exists;
 - }
 - $this->autoCommit = $autocommit;
 - $this->useException = false;
 - if ($this->autoCommit == false) {
 - $this->useException = true;
 - }
 - }
 - /**
 - * Handels errors
 - *
 - * Will throw an exception if this->useException is true (and return false)
 - * Or else dies, printing the argument
 - *
 - * @param string $arg Description of the encountered error
 - * @return bool false
 - */
 - public function handleErr($arg) {
 - if ($this->useException == true) {
 - throw new Exception($arg);
 - return false;
 - } else {
 - die($arg);
 - }
 - }
 - /**
 - * Sets the current operating table - checks against whitelist of tables (throws error if no match)
 - *
 - * @param string $table Name of the white-listed table
 - * @return bool true
 - */
 - public function setCurrentTable($table = null) {
 - if (!in_array($table, $this->tablesWhitelist)) {
 - $this->handleErr("RequestTemplate->setCurrentTable invalid table used: $table");
 - }
 - $this->currentTable = $table;
 - return true;
 - }
 - /* create request entries
 - arguments:
 - $dataArray (string) - user notes to use on event
 - keyName -> ['s', 'value'],
 - $initialInsert (boolean) - will use the ID from the insert statement for subsequent requests
 - $insertIgnore (boolean) - will ignore duplicate unique entries instead of throwing an error
 - */
 - public function insertFields($dataArray, $initialInsert = false, $insertIgnore = false) {
 - if (!isset($this->currentUSER)) {
 - $this->handleErr("No currentUSER defined");
 - }
 - if (is_null($this->currentTable)) {
 - $this->handleErr("RequestTemplate->insertFields no valid table defined");
 - } else if ($this->checkTableField() == false) {
 - $this->handleErr("RequestTemplate->insertFields invalid table used: {$this->currentTable}");
 - }
 - $setStringArry0 = array();
 - $setStringArry1 = array();
 - $arParams = array();
 - $typeString = "";
 - $return = false;
 - // might want to enforce the existance of some fields here
 - foreach ($dataArray as $key => $value) {
 - if ($this->checkTableField($key) == false) {
 - $this->handleErr("RequestTemplate->insertFields Invalid field passed: $key");
 - }
 - if (strtolower($dataArray[$key][1]) == 'null') {
 - $dataArray[$key][1] = null;
 - }
 - $setStringArry0[] = "`$key`";
 - if ($dataArray[$key][0] == "f" && in_array($dataArray[$key][1], $this->myslqFuncWhiteList)) {
 - if (is_null($dataArray[$key][1])) {
 - $setStringArry1[] = 'NULL';
 - } else {
 - $setStringArry1[] = $dataArray[$key][1];
 - }
 - } else {
 - $typeString .= $dataArray[$key][0];
 - $setStringArry1[] = "?";
 - $arParams[] = &$dataArray[$key][1];
 - }
 - }
 - array_unshift($arParams, $typeString);
 - $qryPart0 = implode(", ", $setStringArry0);
 - $qryPart1 = implode(", ", $setStringArry1);
 - $insert = "INSERT";
 - if ($insertIgnore === true) {
 - $insert = "INSERT IGNORE";
 - }
 - $sql = "INSERT INTO `{$this->currentTable}` ($qryPart0) VALUES ($qryPart1)";
 - if ($insertIgnore === true) {
 - $sql .= " ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(id)";
 - }
 - $stmt = $this->mysqli->prepare($sql);
 - if ($stmt) {
 - call_user_func_array(array($stmt, "bind_param"), $arParams);
 - $rc = $stmt->execute();
 - if ($rc === false) {
 - $this->handleErr("RequestTemplate->insertFields->stmt->execute() failed: " . htmlspecialchars($stmt->error));
 - }
 - $return = $stmt->insert_id;
 - if ($initialInsert == true) {
 - $this->currentID = $return;
 - }
 - if ($this->autoCommit == true) {
 - $stmt->close();
 - }
 - } else {
 - $this->handleErr("RequestTemplate->insertFields->stmt->prepare() failed: " . htmlspecialchars($this->mysqli->error));
 - }
 - return $return;
 - }
 - /* update fields on the request
 - arguments:
 - $dataArray (string) - user notes to use on event
 - keyName -> ['s', 'value'],
 - */
 - public function updateFields($dataArray) {
 - $this->checkRequired();
 - if (is_null($this->currentTable)) {
 - $this->handleErr("RequestTemplate->updateFields no valid table defined");
 - } else if ($this->checkTableField() == false) {
 - $this->handleErr("RequestTemplate->updateFields invalid table used: {$this->currentTable}");
 - }
 - $setStringArry = array();
 - $arParams = array();
 - $typeString = "";
 - foreach($dataArray as $key => $value) {
 - if ($this->checkTableField($key) == false) {
 - $this->handleErr("RequestTemplate->updateFields Invalid field passed: $key");
 - }
 - if (strtolower($dataArray[$key][1]) == 'null') {
 - $dataArray[$key][1] = null;
 - }
 - if ($dataArray[$key][0] == "f" && in_array($dataArray[$key][1], $this->myslqFuncWhiteList)) {
 - if (is_null($dataArray[$key][1])) {
 - $setStringArry[] = "`$key` = NULL";
 - } else {
 - $setStringArry[] = "`$key` = {$dataArray[$key][1]}";
 - }
 - } else {
 - $setStringArry[] = "`$key` = ?";
 - $arParams[] = &$dataArray[$key][1];
 - $typeString .= $dataArray[$key][0];
 - }
 - }
 - // add extra integer for id
 - $typeString .= "i";
 - $arParams[] = &$this->currentID;
 - array_unshift($arParams, $typeString);
 - $qryPart = implode(", ", $setStringArry);
 - $sql = "UPDATE `{$this->currentTable}` SET $qryPart WHERE `id` = ?";
 - $stmt = $this->mysqli->prepare($sql);
 - if ($stmt) {
 - call_user_func_array( array($stmt, "bind_param"), $arParams);
 - $rc = $stmt->execute();
 - if( $rc === false ) $this->handleErr("RequestTemplate->updateFields->stmt->execute() failed: " . htmlspecialchars($stmt->error));
 - if($this->autoCommit == true) {
 - $stmt->close();
 - }
 - } else {
 - $this->handleErr("RequestTemplate->updateFields->stmt->prepare() failed: " . htmlspecialchars($this->mysqli->error));
 - }
 - return true;
 - }
 - /**
 - * Checks if a field exists within the current table
 - *
 - * @param string $field name of the field to check for
 - * @return bool true | false (whether the field was found or not)
 - */
 - private function checkTableField($field = false) {
 - $rows = 0;
 - $qry = "SELECT * FROM information_schema.TABLES WHERE TABLE_NAME = ?";
 - if ($field != false) {
 - $qry = "SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?";
 - }
 - if ($stmt = $this->mysqli->prepare($qry)) {
 - if($field != false) {
 - $rc = $stmt->bind_param("ss", $this->currentTable, $field);
 - } else {
 - $rc = $stmt->bind_param("s", $this->currentTable);
 - }
 - if ( $rc === false ) $this->handleErr("RequestTemplate->checkTableField->stmt->bind_param() failed: " . htmlspecialchars($stmt->error));
 - $rc = $stmt->execute();
 - if ( $rc === false ) $this->handleErr("RequestTemplate->checkTableField->stmt->execute() failed: " . htmlspecialchars($stmt->error));
 - $stmt->store_result();
 - $rows = $stmt->num_rows;
 - $stmt->free_result();
 - if($this->autoCommit == true) {
 - $stmt->close();
 - }
 - } else {
 - $this->handleErr("RequestTemplate->checkTableField->stmt->prepare() failed: " . htmlspecialchars($this->mysqli->error));
 - }
 - if ($rows == 1) return true;
 - return false;
 - }
 - /**
 - * Build input object for inserting and updating database fields
 - *
 - * @param array $dataArray array of key names and values to parse
 - * @return array $output array of database column names and their respective inputs
 - */
 - public function buildTableInputs($dataArray) {
 - $output = array();
 - foreach ($dataArray as $key => $value) {
 - if (isset($this->fieldTypes[$key])) {
 - if (isset($this->fieldTypes[$key]["formatting"])) {
 - $formatted = call_user_func_array(array($this, $this->fieldTypes[$key]["formatting"]), array($dataArray[$key]));
 - if (is_null($formatted)) {
 - if (isset($this->fieldTypes[$key]["allow_null_format"]) && $this->fieldTypes[$key]["allow_null_format"] === true) {
 - $dataArray[$key] = $formatted;
 - }
 - } else {
 - $dataArray[$key] = $formatted;
 - }
 - }
 - $output[$this->fieldTypes[$key]["db_field"]] = array($this->fieldTypes[$key]["db_type"], $dataArray[$key]);
 - }
 - }
 - return $output;
 - }
 - /**
 - * Checks for a database connection, creates one if it does not exist
 - *
 - * @return object A mysqli connection instance
 - */
 - public function checkDBConn() {
 - if (is_null($this->mysqli)) {
 - $db = new Connection();
 - $db->connect();
 - $this->mysqli = $db->get_connection();
 - }
 - return $this->mysqli;
 - }
 - }
 - ?>
 
Advertisement
 
                    Add Comment                
                
                        Please, Sign In to add comment