/** * A test callback function to be used in the test class below for * ensuring that custom datatype callback features are handled * correctly. * * @param MDB2 $db The MDB2 database reource object. * @param string $method The name of the MDB2_Driver_Datatype_Common method * the callback function was called from. One of * "getValidTypes", "convertResult", "getDeclaration", * "compareDefinition", "quote" and "mapPrepareDatatype". * See {@link MDB2_Driver_Datatype_Common} for the * details of what each method does. * @param array $aParameters An array of parameters, being the parameters that * were passed to the method calling the callback * function. * @return mixed Returns the appropriate value depending on the method that * called the function. See {@link MDB2_Driver_Datatype_Common} * for details of the expected return values of the five possible * calling methods. */ function datatype_test_callback(&$db, $method, $aParameters) { // Ensure the datatype module is loaded if (is_null($db->datatype)) { $db->loadModule('Datatype', null, true); } // Lowercase method names for PHP4/PHP5 compatibility $method = strtolower($method); switch ($method) { // For all cases, return a string that identifies that the // callback method was able to call to the appropriate point case 'getvalidtypes': return 'datatype_test_callback::getvalidtypes'; case 'convertresult': return 'datatype_test_callback::convertresult'; case 'getdeclaration': return 'datatype_test_callback::getdeclaration'; case 'comparedefinition': return 'datatype_test_callback::comparedefinition'; case 'quote': return 'datatype_test_callback::quote'; case 'mappreparedatatype': return 'datatype_test_callback::mappreparedatatype'; } }
/** * Funcion que muestra el listado de medicamentos * @return void */ function listar() { global $db; $titulo = ''; if ($_REQUEST['tipo'] == '1') { $titulo = 'MEDICAMENTOS'; } elseif ($_REQUEST['tipo'] == '2') { $titulo = 'LABORATORIO'; } elseif ($_REQUEST['tipo'] == '3') { $titulo = 'IMAGENOLOGIA'; } elseif ($_REQUEST['tipo'] == '4') { $titulo = 'PROCEDIMIENTO'; } // Database connection $odbconn = MDB2::connect($db['dsn'], $db['opts']); $odbconn->setFetchMode(MDB2_FETCHMODE_ASSOC); $sql = "SELECT *\n FROM {$this->tabla}\n WHERE tipo = '{$_REQUEST['tipo']}'\n "; if (isset($_REQUEST['buscar'])) { if ($_REQUEST['palabra']) { $sql .= " AND( upper(nombre) LIKE '%" . strtoupper($_REQUEST['palabra']) . "%')"; $show = true; } } $sql .= " ORDER BY id ASC"; $pager_options = array('mode' => 'Sliding', 'perPage' => 16, 'delta' => 2, 'extraVars' => array('a' => $_REQUEST['a'])); $data = Pager_Wrapper_MDB2($odbconn, $sql, $pager_options); // Mensaje a mostrar en el template $msj = flashData(); // Variables usadas en el template include getTemplate('sugerencia.lista.php'); return; }
public function myDB($host, $user, $pwd, $db, $port) { $dsn = array('phptype' => 'pgsql', 'username' => $user, 'password' => $pwd, 'hostspec' => $host, 'database' => $db, 'port' => $port); if ($this->log) { $this->writeLog(print_r($dsn, true)); } $options = array('result_buffering' => false); $this->db =& MDB2::factory($dsn, $options); //$this->db=& MDB2::connect($dsn,$options); if (!$this->db || PEAR::isError($this->db)) { if ($this->log) { $this->writeLog('Connect Error: ' . $dns); } $this->dbFehler('Connect ' . print_r($dsn, true), $this->db->getMessage()); die($this->db->getMessage()); } $this->db->setFetchMode(MDB2_FETCHMODE_ASSOC); if ($this->log) { $this->writeLog('Connect: ok '); } $sql = 'SELECT version()'; $rs = $this->getOne($sql); if ($this->log) { $this->writeLog(print_r($rs, true)); } preg_match('/PostgreSQL\\s*([\\d]+)\\.([\\d]+)\\..*/', $rs['version'], $ver); if ($ver[1] == '9' and $ver[2] >= '3' or $ver[1] >= '10') { $this->JVer = true; } if ($this->log) { $this->writeLog(print_r($ver, true) . "!" . $this->JVer . '!'); } return $this->db; }
/** * Connect to databases, but create instance not before the first time * a query gets executed. */ private function connectDbLazy() { $this->connection = MDB2::factory($this->dsn); if (PEAR::isError($this->connection)) { die("Error while lazy connecting: " . $this->connection->getMessage() . "\ndsn was: " . print_r($this->dsn) . "\n"); } }
/** * add message data * * @param array $data */ function perform(&$data) { $mid = $this->B->db->nextId($this->B->sys['db']['table_prefix'] . 'earchive_messages'); if (MDB2::isError($mid)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } $sql = ' INSERT INTO ' . $this->B->sys['db']['table_prefix'] . 'earchive_messages (mid,lid,sender,subject,mdate,body,folder) VALUES (' . $mid . ', ' . $data['lid'] . ', "' . $data['sender'] . '", "' . $data['subject'] . '", "' . $data['mdate'] . '", "' . $data['body'] . '", "' . $data['folder'] . '")'; $result = $this->B->db->query($sql); if (MDB2::isError($result)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } return $mid; }
function db_connect($dbtype = 'mysql') { $dbhost = 'localhost'; $dbuser = '******'; $dbpass = '******'; if ($dbtype == 'pear') { $dsn = array('phptype' => 'mysql', 'username' => $dbuser, 'password' => $dbpass, 'hostspec' => $dbhost); $options = array('debug' => 2, 'portability' => MDB2_PORTABILITY_ALL); // uses MDB2::factory() to create the instance // and also attempts to connect to the host $mdb2 = MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { error($mdb2->getMessage()); } return $mdb2; } else { if ($dbtype == 'mysql') { $mysql_conn = mysqli_connect($dbhost, $dbuser, $dbpass); if (mysqli_connect_errno()) { error("MySQL : Connect failed: %s\n" . mysqli_connect_error()); } return $mysql_conn; } else { if ($dbtype == 'postgres') { $postgres_conn = pg_connect("host={$dbhost} user={$dbuser} password={$dbpass}"); if (!$postgres_conn) { error("PostGres : Connect failed: %s"); } return $postgres_conn; } } } }
public function createInstance() { require_once 'MDB2.php'; $dsn = $this->settings['db.dsn']; $db = MDB2::factory($dsn); return $db; }
static function sanitizeDb($db) { if (is_string($db)) { require_once 'MDB2.php'; // $dsn = MDB2::parseDSN($db); $db = MDB2::connect($db); } else { if (is_object($db) && is_subclass_of($db, 'MDB2_Driver_Common')) { /* MDB2 driver */ } else { if (is_array($db) && count(array_diff(array(0, 1, 2, 3, 4), array_keys($db))) == 0) { $dsnString = $db[0] . '://' . $db[2] . ':' . $db[3] . '@' . $db[1] . '/' . $db[4]; $db = MDB2::connect($dsnString); } else { if (is_array($db) && array_key_exists('phptype', $db)) { $db = MDB2::connect($db); } else { throw new Exception('Invalid database'); } } } } $dsn = MDB2::parseDSN($db->dsn); if (!$dsn['database']) { // sometimes the database name is not set here, so try to recover $dsn['database'] = $db->database_name; } return array($db, $dsn); }
function conectar() { if (!isset($mdb2)) { //Local $db_name = 'root'; $db_password = ''; $db_server = 'localhost'; $db_database = 'coopcrucial'; //Nabica /*$db_name = 'coopcrucial'; $db_password = '******'; $db_server = 'coopcrucial.db.5840507.hostedresource.com'; $db_database = 'coopcrucial';*/ $dsn = 'mysql://' . $db_name . ':' . $db_password . '@' . $db_server . '/' . $db_database; try { $mdb2 =& MDB2::factory($dsn, true); if (MDB2::isError($mdb2)) { die($mdb2->getmessage() . ' - ' . $mdb2->getUserInfo()); } else { $mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC); } $mdb2 = array('mdb2' => $mdb2, 'dsn' => $dsn); } catch (Exception $exc) { echo $exc->getTraceAsString(); } } return $mdb2; }
private function __construct() { Plank_Logger::log('Singleton', get_class($this) . ' singleton created.', L_TRACE); $config = Plank_Config::getInstance(); $config = $config->getArea('database'); if (!$config || !isset($config['connections'])) { throw new Plank_Exception_Database_Config('Databases not configured'); } $connections = explode(',', $config['connections']); foreach ($connections as $connection) { if (isset($config['dsn_' . $connection])) { $this->connections[$connection] = MDB2::factory($config['dsn_' . $connection]); if (PEAR::isError($this->connections[$connection])) { throw new Plank_Exception_Database('DB Error! ' . $this->connections[$connection]->getMessage() . ' ' . $this->connections[$connection]->getUserInfo()); } if (SHOWDEBUG) { $this->connections[$connection]->setOption('debug', 1); $this->connections[$connection]->setOption('log_line_break', "<br/>"); } $this->connections[$connection]->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE); $this->connections[$connection]->setFetchMode(MDB2_FETCHMODE_ASSOC); if (PEAR::isError($this->connections[$connection])) { throw new Plank_Exception_Database_Connection('Error connecting ' . $connection . ': ' . $this->connections[$connection]->getMessage() . ' ' . $this->connections[$connection]->getUserInfo()); } } else { throw new Plank_Exception_Database_Config('No DSN for DB Connection ' . $connection); } } }
/** * This function is a replacement for ADONewConnection, it does some * basic additional configuration and prepares the table prefix stuff * * @param $conf usually $conf['database'] in Flyspray * @return object */ function &NewDatabase($conf = array()) { if (!is_array($conf) || extract($conf, EXTR_REFS | EXTR_SKIP) < 5) { die('Flyspray was unable to connect to the database. ' . 'Check your settings in flyspray.conf.php'); } $dbpass = rawurlencode($dbpass); if ($dbtype == 'sqlite') { $dsn = "{$dbtype}:///{$dbname}?mode=0666"; } else { $dsn = "{$dbtype}://{$dbuser}:{$dbpass}@{$dbhost}/{$dbname}?charset=utf8"; } $db =& MDB2::factory($dsn); $db->loadModule('Extended', 'x', false); if (defined('IN_UPGRADER') || defined('IN_SETUP')) { $db->loadModule('Manager'); } $dbprefix = isset($dbprefix) ? $dbprefix : ''; if ($db === false || !empty($dbprefix) && !preg_match('/^[a-z][a-z0-9_]+$/i', $dbprefix)) { die('Flyspray was unable to connect to the database. ' . 'Check your settings in flyspray.conf.php'); } define('DB_PREFIX', $dbprefix); $db->setFetchMode(MDB2_FETCHMODE_ASSOC); $db->setOption('debug', true); $db->setOption('debug_handler', '_table_prefix'); $db->setOption('quote_identifier', true); // upgrader can handle that on its own if (!defined('IN_UPGRADER') && !defined('IN_SETUP') || defined('DEBUG_SQL')) { $db->setErrorHandling(PEAR_ERROR_CALLBACK, 'show_dberror'); } return $db; }
function R3AppInitDB() { global $mdb2; global $dsn; require_once 'MDB2.php'; if (!isset($dsn) || $dsn == '') { throw new Exception('Missing $dsn'); } $txtDsn = $dsn['dbtype'] . '://' . $dsn['dbuser'] . ':' . $dsn['dbpass'] . '@' . $dsn['dbhost'] . '/' . $dsn['dbname']; $db = ezcDbFactory::create($txtDsn); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); PEAR::setErrorHandling(PEAR_ERROR_EXCEPTION); $mdb2 = MDB2::singleton($txtDsn); // Needed by user manager and import/export ezcDbInstance::set($db); if (isset($dsn['charset'])) { $db->exec("SET client_encoding TO '{$dsn['charset']}'"); $mdb2->exec("SET client_encoding TO '{$dsn['charset']}'"); } if (isset($dsn['search_path'])) { $db->exec("SET search_path TO {$dsn['search_path']}, public"); $mdb2->exec("SET search_path TO {$dsn['search_path']}, public"); } $db->exec("SET datestyle TO ISO"); $mdb2->exec("SET datestyle TO ISO"); }
/** * add user * * @param array $data * @return int user id or false on error */ function perform($data) { $this->B->{$data}['error'] = FALSE; $error =& $this->B->{$data}['error']; if ($this->login_exists($data['user_data']['login']) > 0) { $error = 'Login exists'; return FALSE; } $uid = $this->B->db->nextId($this->B->sys['db']['table_prefix'] . 'user_users'); if (MDB2::isError($uid)) { trigger_error($uid->getMessage() . "\n" . $uid->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); $error = 'Unexpected error'; return FALSE; } $sql = ' INSERT INTO ' . $this->B->sys['db']['table_prefix'] . 'user_users (uid,forename,lastname,email,login,passwd,status,rights) VALUES (' . $uid . ', "' . $data['user_data']['forename'] . '", "' . $data['user_data']['lastname'] . '", "' . $data['user_data']['email'] . '", "' . $data['user_data']['login'] . '", "' . $data['user_data']['passwd'] . '", ' . $data['user_data']['status'] . ', ' . $data['user_data']['rights'] . ')'; $res = $this->B->db->query($sql); if (MDB2::isError($res)) { trigger_error($res->getMessage() . "\n" . $res->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); $error = 'Unexpected error'; return FALSE; } return $uid; }
/** * add list data in db table * * @param array $data */ function perform(&$data) { // get list messages attachment folder string $list_folder = commonUtil::unique_md5_str(); if (!@mkdir(SF_BASE_DIR . '/data/earchive/' . $list_folder, SF_DIR_MODE)) { trigger_error("Cannot create list messages attachment folder! Contact the administrator.\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } $lid = $this->B->db->nextId($this->B->sys['db']['table_prefix'] . 'earchive_lists'); if (MDB2::isError($lid)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } $sql = ' INSERT INTO ' . $this->B->sys['db']['table_prefix'] . 'earchive_lists (lid,name,email,emailserver,description,folder,status) VALUES (' . $lid . ', "' . $data['name'] . '", "' . $data['email'] . '", "' . $data['emailserver'] . '", "' . $data['description'] . '", "' . $list_folder . '", ' . $data['status'] . ')'; $result = $this->B->db->query($sql); if (MDB2::isError($result)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } return TRUE; }
/** * Assign array with message attachments data * * @param array $data */ function perform(&$data) { if (empty($data['mid']) || empty($data['var'])) { trigger_error("'mid' or 'var' is empty!\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } // get var name to store the result $this->B->{$data}['var'] = array(); $_result =& $this->B->{$data}['var']; $comma = ''; foreach ($data['fields'] as $f) { $_fields .= $comma . $f; $comma = ','; } $sql = "\n SELECT\n {$_fields}\n FROM\n {$this->B->sys['db']['table_prefix']}earchive_attach\n WHERE\n mid={$data['mid']} \n ORDER BY\n file ASC"; $result = $this->B->db->query($sql); if (MDB2::isError($result)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); } $_result = array(); if (is_object($result)) { while ($row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { $tmp = array(); foreach ($data['fields'] as $f) { $tmp[$f] = stripslashes($row[$f]); } $_result[] = $tmp; } } return TRUE; }
function check_db_error($sth, $file, $line) { if (MDB2::isError($sth)) { $error_str = "File: {$file} (line {$line})<br />\n " . "<strong>" . $sth->getMessage() . "</strong><br />\n" . $sth->getUserInfo() . "<br />\n"; die($error_str); } }
/** * Funcion que muestra el listado de manuales * @return void */ function listar() { global $db; $show = false; $display = "style=\"display:none;\""; // Database connection $odbconn = MDB2::connect($db['dsn'], $db['opts']); $odbconn->setFetchMode(MDB2_FETCHMODE_ASSOC); $sql = "SELECT *\n FROM {$this->tabla}\n WHERE 1=1 "; if (isset($_REQUEST['buscar'])) { if ($_REQUEST['palabra']) { $sql .= " AND( upper(nombre) LIKE '%" . strtoupper($_REQUEST['palabra']) . "%' \n OR codigo LIKE '%{$_REQUEST['palabra']}%'\n OR cups LIKE '%{$_REQUEST['palabra']}%') "; $show = true; } if ($_REQUEST['manual']) { $sql .= " AND manual = '{$_REQUEST['manual']}' "; $show = true; } } if ($show === true) { $display = "style=\"display:inline;\""; } $pager_options = array('mode' => 'Sliding', 'perPage' => 16, 'delta' => 2, 'extraVars' => array('a' => $_REQUEST['a'])); $data = Pager_Wrapper_MDB2($odbconn, $sql, $pager_options); // Variable para el template $Manual = new Manual(); $smanual = $Manual->lista(); $manual = arregloLista($smanual); $idmanual = isset($_REQUEST['manual']) ? $_REQUEST['manual'] : ''; // Mensaje a mostrar en el template $msj = flashData(); include getTemplate('tarifa.lista.php'); return; }
/** * Check the login and password * @return void */ function login() { global $db; $usuario = sanitize($_POST['usuario']); $clave = sanitize($_POST['clave']); $sql = "SELECT id,usuario,nombre1,apellido1,id_rol,tipo\n FROM usuario \n WHERE usuario = '{$usuario}'\n AND clave = MD5('{$clave}')"; $odbconn = MDB2::connect($db['dsn'], $db['opts']); $odbconn->setFetchMode(MDB2_FETCHMODE_ASSOC); $rst = $odbconn->queryRow($sql); $odbconn->disconnect(); if (PEAR::isError($rst)) { return false; } if ($rst) { session_start(); $_SESSION['user']['startTime'] = date("Y-m-d H:i"); $_SESSION['user']['id_usuario'] = $rst['id']; $_SESSION['user']['usuario'] = $rst['usuario']; $_SESSION['user']['nombres'] = $rst['nombre1']; $_SESSION['user']['apellidos'] = $rst['apellido1']; $_SESSION['user']['rol'] = $rst['id_rol']; $_SESSION['user']['tipo'] = $rst['tipo']; $Modulo = new Modulo(); $_SESSION['perms'] = $Modulo->getModulosPermitidos($rst['id_rol']); header('Location: ../../index.php'); } else { header("Location: ../../login.php?login=false"); } }
/** * Delete email list data and attachement folder * * @param array $data */ function perform(&$data) { if (empty($data['lid'])) { trigger_error("'lid' is empty!\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } $set = ''; $comma = ''; foreach ($data['data'] as $key => $val) { $set .= $comma . $key . '=' . $val; $comma = ','; } $sql = ' UPDATE ' . $this->B->sys['db']['table_prefix'] . 'earchive_lists SET ' . $set . ' WHERE lid=' . $data['lid']; $result = $this->B->db->query($sql); if (MDB2::isError($result)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } return TRUE; }
/** * Create a new instance of a default I2CE table user access mechanism */ public function __construct() { $protocol = substr(get_class($this), 16); if (!$protocol) { $protocol = 'DEFAULT'; } $this->protocol = $protocol; $init = I2CE::getUserAccessInit($protocol); if (empty($init)) { $options = array(); } else { $options = json_decode($init, true); if (!is_array($options)) { I2CE::raiseError("Invalid user access initilization string"); $options = array(); } } if (!array_key_exists('admin_user', $options)) { $options['admin_user'] = '******'; } if (!array_key_exists('admin_pass', $options)) { $options['admin_pass'] = MDB2::singleton()->dsn['password']; } if (!array_key_exists('admin_details', $options) || !is_array($options['admin_details'])) { $options['admin_details'] = array(); } if (!array_key_exists('auto_login', $options)) { $options['auto_login'] = 0; } if (!array_key_exists('auto_login_user', $options)) { $options['auto_login_user'] = false; } $this->options = $this->ensureDefaultOptions($options); }
/** * update user data * * @param array $data * @return bool true or false on error */ function perform($data) { $this->B->{$data}['error'] = FALSE; $error =& $this->B->{$data}['error']; $set = ''; $comma = ''; foreach ($data['fields'] as $key => $val) { $set .= $comma . $key . '="' . $this->B->db->escape($val) . '"'; $comma = ','; } $sql = ' UPDATE ' . $this->B->sys['db']['table_prefix'] . 'user_users SET ' . $set . ' WHERE uid=' . $data['user_id']; $result = $this->B->db->query($sql); if (MDB2::isError($result)) { trigger_error($result->getMessage() . "\n" . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); $error = 'Unexpected error'; return FALSE; } return TRUE; }
/** * Check login data and set session vars and url forward on success * * @param array $data */ function perform($data) { $passwd = md5($data['passwd']); $sql = "SELECT \n uid,\n rights\n FROM\n {$this->B->sys['db']['table_prefix']}user_users\n WHERE\n login='******'login']}'\n AND\n passwd='{$passwd}'\n AND\n status=2"; $result = $this->B->db->query($sql); if (MDB2::isError($result)) { trigger_error($result->getMessage() . "\n\nINFO: " . $result->userinfo . "\n\nFILE: " . __FILE__ . "\nLINE: " . __LINE__, E_USER_ERROR); return FALSE; } if ($result->numRows() == 1) { $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC); $this->B->session->set('logged_id_user', $row['uid']); $this->B->session->set('logged_user_rights', $row['rights']); $admin = ''; if (SF_SECTION == 'admin') { $admin = '?admin=1'; } $query = ''; if (isset($data['forward_urlvar'])) { $amp = '?'; if (!empty($admin)) { $amp = '&'; } $query = $amp . base64_decode($data['forward_urlvar']); } @header('Location: ' . SF_BASE_LOCATION . '/index.php' . $admin . $query); exit; } else { return FAlSE; } }
public function dbh($dsn = null, $opt = null) { //init if (null != $dsn) { $this->dsn = $dsn; } if (null != $opt) { $this->opt = $opt; } //connect => $dsn = 'pgsql://*****:*****@localhost/thedb'; $this->dbh =& MDB2::factory($this->dsn, $this->opt); //sanity if (self::err($this->dbh, "dbh() : init-db")) { return null; } //re-init $this->dbh->setFetchMode(MDB2_FETCHMODE_ASSOC); //more options $this->dbh->setOption('result_buffering', true); $this->dbh->setOption('multi_query', true); //set here the utf-8 $utf8[] = " SET NAMES 'utf8' COLLATE utf8_unicode_ci "; $utf8[] = " SET character_set_client='utf8' "; $utf8[] = " SET character_set_connection='utf8' "; for ($i = 0; $i < @count($utf8); $i++) { $bfsql = trim($utf8[$i]); self::query($bfsql, "ERROR: {$bfsql}"); } //give it back ;-) return $this->dbh; }
/** *Renames a child node * @param I2CE_MagicDataNode $node *@param string $old *@param string $new *@returns boolean. True on success, false on failure */ public function renameChild($node, $old, $new) { if ($node instanceof I2CE_MagicData) { $parentPath = '/'; $offset = strlen('/' . $old) + 1; $fullOffset = strlen($node->getPath(true) . '/' . $old); // if $old ='old', results in calling SUBSTR(parent,5) //so if parent = '/old/path' then substr(parent,5) = '/path' //we want to result in /new/path } else { $parentPath = $node->getPath(false); //e.g. $offset = strlen($node->getPath(false) . '/' . $old) + 1; $fullOffset = strlen($node->getPath(true) . '/' . $old); //child: if $old = 'old' and $node='/some', then calling SUBSTR(parent, 10) //so if parent = /some/old/path then substr(parent,10) = /path //we want to result in /some/new/path } $newPath = mysql_real_escape_string($this->getChildPath($node, $new, false)); $newFullPath = mysql_real_escape_string($this->getChildPath($node, $new, true)); $oldPath = mysql_real_escape_string($this->getChildPath($node, $old, false)); $qry_node = "UPDATE config_alt SET name = '" . mysql_real_escape_string($new) . "' , path_hash = '" . mysql_real_escape_string($this->getHash($node, $new)) . "' " . "WHERE parent = '" . mysql_real_escape_string($parentPath) . "' AND name = '" . mysql_real_escape_string($old) . "'"; //change direct children $qry_child = "UPDATE config_alt SET " . " path_hash = MD5(CONCAT('{$newFullPath}', '/',name)) " . ", parent = '{$newPath}' " . "WHERE parent = '{$oldPath}'"; //change descendents $qry_desc = "UPDATE config_alt SET " . " path_hash = MD5( CONCAT('{$newFullPath}', SUBSTR(parent,{$offset}) , '/',name)) " . ", parent = CONCAT('{$newPath}', SUBSTR(parent,{$offset}) ) " . "WHERE parent LIKE '{$oldPath}/%'"; $this->db->exec($qry_node); $this->db->exec($qry_child); $this->db->exec($qry_desc); return true; }
/** | | @init | | @description | - init | | @parameters | - | | | @return | - | **/ public function init() { //create connection debug("init() : start init [ self::{$_Dsn} ]"); //try self::$_Mdb =& MDB2::factory(self::$_Dsn, self::$_Opt); //sanity-chk if (self::err(self::$_Mdb, "init::FAILED")) { return null; } //misc options set here self::$_Mdb->setFetchMode(MDB2_FETCHMODE_ASSOC); //more options self::$_Mdb->setOption('result_buffering', true); self::$_Mdb->setOption('multi_query', true); //set here the utf-8 $utf8[] = " SET NAMES 'utf8' COLLATE utf8_unicode_ci "; $utf8[] = " SET character_set_client='utf8' "; $utf8[] = " SET character_set_connection='utf8' "; for ($i = 0; $i < @count($utf8); $i++) { $bfsql = trim($utf8[$i]); self::query($bfsql, "ERROR: {$bfsql}"); debug("init() : utf-8 [ {$bfsql} ]"); } debug("init() : done init [ self::{$_Mdb} ]"); return self::$_Mdb; }
function db_init($user, $passwd, $host, $database, $die_on_error = TRUE, $charset = "UTF8") { global $db; // DSN string must have new_link=true in order for multiple connections with different charsets to work $dsn = "mysql://{$user}:{$passwd}@{$host}/{$database}?new_link=true"; $db = MDB2::factory($dsn); if (PEAR::isError($db)) { $msg = "Unable to initialise database. Please try again later."; $msg = "{$msg}: {$db->message} . ' ' . {$db->userinfo}"; $db = NULL; db_log(1, $msg); if ($die_on_error) { if (defined('UNIT_TEST')) { print $msg . "\n"; } exit; } } else { $db->setCharset($charset); // remove MDB2_PORTABILITY_EMPTY_TO_NULL - Without turning this setting off, MDB2 will treat empty strings (i.e. '') // as NULLs when storing. We prefer to use empty strings for some fields. // remove MDB2_PORTABILITY_FIX_CASE - keep associative fields case sensitive rather than all lower case $db->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL ^ MDB2_PORTABILITY_FIX_CASE); } }
/** * 次のシーケンス値を取得する. * * @param string $seq_name 取得するシーケンス名 * @param integer 次のシーケンス値 */ function nextVal($seq_name) { $dsn = array('phptype' => DB_TYPE, 'username' => DB_USER, 'password' => DB_PASSWORD, 'protocol' => 'tcp', 'hostspec' => DB_SERVER, 'port' => DB_PORT, 'database' => DB_NAME); // SQL Azure では必ず新しいセッションを使用する $_conn = MDB2::connect($dsn, $options); return $_conn->nextID($seq_name, false); }
/** * A factory method which returns the currently supported best advisory lock * instance. * * @return OA_DB_AdvisoryLock Reference to an OA_DB_AdvisoryLock object. */ function &factory($sType = null) { if (is_null($sType)) { $oDbh =& OA_DB::singleton(); if (PEAR::isError($oDbh)) { OA::debug('Error connecting to database to obtain locking object. Native error follows:', PEAR_LOG_ERR); OA::debug($oDbh, PEAR_LOG_ERR); OA::debug('Will re-try connection...', PEAR_LOG_ERR); $retryCount = 0; while (PEAR::isError($oDbh) && $retryCount < 6) { $retryCount++; sleep(10); OA::debug('Re-try connection attempt #' . $retryCount, PEAR_LOG_ERR); $oDbh =& OA_DB::singleton(); } if (PEAR::isError($oDbh)) { OA::debug('Failed in re-try attempts to connect to database. Aborting.', PEAR_LOG_CRIT); exit; } } $aDsn = MDB2::parseDSN($oDbh->getDSN()); $sType = $aDsn['phptype']; } include_once MAX_PATH . '/lib/OA/DB/AdvisoryLock/' . $sType . '.php'; $sClass = "OA_DB_AdvisoryLock_" . $sType; $oLock = new $sClass(); if (!$oLock->_isLockingSupported()) { // Fallback to file based locking if the current class won't work $oLock =& OA_DB_AdvisoryLock::factory('file'); } return $oLock; }
public static function alreadyProcessed($node) { if (!is_array($return = self::getNodeHash($node))) { return null; } list($relationship, $hash) = $return; if (!is_string($relationship) || !is_string($hash)) { $this->raiseError("Bad parameters"); return null; } if (self::$lookup_stmt === null) { $db = MDB2::singleton(); self::$lookup_stmt = $db->prepare("SELECT id FROM form_relationship_importer WHERE relationship = ? and hash= ?", array('text', 'text'), array('text'), MDB2_PREPARE_RESULT); if (I2CE::pearError(self::$lookup_stmt, "Could not prepare lookup statement")) { return null; } } if (!self::$lookup_stmt) { return null; } $results = self::$lookup_stmt->execute(array($relationship, $hash)); $row = $results->fetchRow(); if (!isset($row) || I2CE::pearError($row, "Error getting form id:")) { return false; } return $row->id; }
/** * Funcion que muestra el listado de medicamentos * @return void */ function listar() { global $db; // Database connection $odbconn = MDB2::connect($db['dsn'], $db['opts']); $odbconn->setFetchMode(MDB2_FETCHMODE_ASSOC); $sql = "SELECT *\n FROM {$this->tabla}\n WHERE 1=1 "; if (isset($_REQUEST['buscar'])) { if ($_REQUEST['palabra']) { $sql .= " AND( upper(generico) LIKE '%" . strtoupper($_REQUEST['palabra']) . "%' \n OR codigo LIKE '%{$_REQUEST['palabra']}%'\n )"; $show = true; } if ($_REQUEST['forma']) { $sql .= " AND codformfarm = '{$_REQUEST['forma']}' "; $show = true; } } $pager_options = array('mode' => 'Sliding', 'perPage' => 16, 'delta' => 2, 'extraVars' => array('a' => $_REQUEST['a'])); $data = Pager_Wrapper_MDB2($odbconn, $sql, $pager_options); // Variables usadas en el template $ltipo = $this->listaTipoForma(); $tipo = arregloLista($ltipo); $idforma = isset($_REQUEST['forma']) ? $_REQUEST['forma'] : ''; include getTemplate('medicamento.lista.php'); return; }