function getSampleData($row) { $data = array(); $data['user_name'] = 'user_' . $row; $data['user_password'] = '******'; $data['subscribed'] = $row % 2 ? true : false; $data['user_id'] = $row; $data['quota'] = strval($row / 100); $data['weight'] = sqrt($row); $data['access_date'] = MDB2_Date::mdbToday(); $data['access_time'] = MDB2_Date::mdbTime(); $data['approved'] = MDB2_Date::mdbNow(); return $data; }
function isInYear($year, $field) { // The value of $year is got from get variable, so we must chech that it // is really a integer with correct value if (!is_int(intval($year)) || $year < 2000) { $this->debugger->error("The year value is not correct", "isInYear"); } $yearStarts = mktime(0, 0, 0, 1, 1, $year); $yearEnds = mktime(0, 0, 0, 1, 1, $year + 1); return " {$field} >= '" . MDB2_Date::unix2Mdbstamp($yearStarts) . "' AND {$field} < '" . MDB2_Date::unix2Mdbstamp($yearEnds) . "' "; }
/** * Test replace query * * The replace method emulates the replace query of mysql */ function testReplace() { if (!$this->supported('replace')) { return; } $row = 1234; $data = $this->getSampleData($row); $fields = array('user_name' => array('value' => "user_{$row}", 'type' => 'text'), 'user_password' => array('value' => $data['user_password'], 'type' => 'text'), 'subscribed' => array('value' => $data['subscribed'], 'type' => 'boolean'), 'user_id' => array('value' => $data['user_id'], 'type' => 'integer', 'key' => 1), 'quota' => array('value' => $data['quota'], 'type' => 'decimal'), 'weight' => array('value' => $data['weight'], 'type' => 'float'), 'access_date' => array('value' => $data['access_date'], 'type' => 'date'), 'access_time' => array('value' => $data['access_time'], 'type' => 'time'), 'approved' => array('value' => $data['approved'], 'type' => 'timestamp')); $result = $this->db->replace('users', $fields); if (PEAR::isError($result)) { $this->assertTrue(false, 'Replace failed'); } if ($this->db->supports('affected_rows')) { $affected_rows = $result; $this->assertEquals(1, $result, "replacing a row in an empty table returned incorrect value"); } $result =& $this->db->query('SELECT ' . implode(', ', array_keys($this->fields)) . ' FROM users', $this->fields); if (PEAR::isError($result)) { $this->assertTrue(false, 'Error selecting from users' . $result->getMessage()); } $this->verifyFetchedValues($result, 0, $data); $row = 4321; $fields['user_name']['value'] = $data['user_name'] = 'user_' . $row; $fields['user_password']['value'] = $data['user_password'] = '******'; $fields['subscribed']['value'] = $data['subscribed'] = $row % 2 ? true : false; $fields['quota']['value'] = $data['quota'] = strval($row / 100); $fields['weight']['value'] = $data['weight'] = sqrt($row); $fields['access_date']['value'] = $data['access_date'] = MDB2_Date::mdbToday(); $fields['access_time']['value'] = $data['access_time'] = MDB2_Date::mdbTime(); $fields['approved']['value'] = $data['approved'] = MDB2_Date::mdbNow(); $result = $this->db->replace('users', $fields); if (PEAR::isError($result)) { $this->assertTrue(false, 'Replace failed'); } if ($this->db->supports('affected_rows')) { $this->assertEquals(2, $result, "replacing a row returned incorrect result"); } $result =& $this->db->query('SELECT ' . implode(', ', array_keys($this->fields)) . ' FROM users', $this->fields); if (PEAR::isError($result)) { $this->assertTrue(false, 'Error selecting from users' . $result->getMessage()); } $this->verifyFetchedValues($result, 0, $data); $this->assertTrue(!$result->valid(), 'the query result did not seem to have reached the end of result as expected'); $result->free(); }
/** * convert a MDB2 timestamp into a unix timestamp * * @param integer $mdb_timestamp a valid MDB2 timestamp * @return string unix timestamp with the time stored in the MDB2 format * @access public */ function mdbstamp2Unix($mdb_timestamp) { $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp); return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], 0); }
/** * http://pear.php.net/bugs/bug.php?id=946 */ function testBug946() { $data = array(); $total_rows = 5; $prepared_query = $this->db->prepare('INSERT INTO users (user_name, user_password, subscribed, user_id, quota, weight, access_date, access_time, approved) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', $this->types); for ($row = 0; $row < $total_rows; $row++) { $data[$row]['user_name'] = "user_{$row}"; $data[$row]['user_password'] = '******'; $data[$row]['subscribed'] = (bool) ($row % 2); $data[$row]['user_id'] = $row; $data[$row]['quota'] = sprintf("%.2f", strval(1 + ($row + 1) / 100)); $data[$row]['weight'] = sqrt($row); $data[$row]['access_date'] = MDB2_Date::mdbToday(); $data[$row]['access_time'] = MDB2_Date::mdbTime(); $data[$row]['approved'] = MDB2_Date::mdbNow(); $this->insertTestValues($prepared_query, $data[$row]); $result = $this->db->execute($prepared_query); if (MDB2::isError($result)) { $this->assertTrue(false, 'Error executing prepared query' . $result->getMessage()); } } $this->db->freePrepared($prepared_query); $this->db->setLimit(3, 1); $result = $this->db->query('SELECT * FROM users'); $numrows = $result->numRows(); while ($row = $result->fetchRow()) { if (MDB2::isError($row)) { $this->assertTrue(false, 'Error fetching a row' . $row->getMessage()); } } $result->free(); $result = $this->db->query('SELECT * FROM users'); $numrows = $result->numRows(); while ($row = $result->fetchRow()) { if (MDB2::isError($row)) { $this->assertTrue(false, 'Error fetching a row' . $row->getMessage()); } } $result->free(); }
/** * LiveUser_Auth_Container_MDB2::readUserData() * * Reads auth_user_id, passwd, is_active flag * lastlogin timestamp from the database * If only $handle is given, it will read the data * from the first user with that handle and return * true on success. * If $handle and $passwd are given, it will try to * find the first user with both handle and password * matching and return true on success (this allows * multiple users having the same handle but different * passwords - yep, some people want this). * If no match is found, false is being returned. * * @param string $handle * @param boolean $passwd * @return boolean */ function readUserData($handle, $passwd = false) { if (!$this->init_ok) { return false; } $success = false; $fields = array(); foreach ($this->authTableCols as $key => $value) { $fields[] = $value['name'] . ' AS ' . $key; $types[] = $value['type']; } if ($passwd !== false) { // If $passwd is set, try to find the first user with the given // handle and password. $sql = 'SELECT ' . implode(',', $fields) . ' FROM ' . $this->authTable . ' WHERE ' . $this->authTableCols['handle']['name'] . '=' . $this->dbc->quote($handle, $this->authTableCols['handle']['type']) . ' AND ' . $this->authTableCols['passwd']['name'] . '=' . $this->dbc->quote($this->encryptPW($passwd), $this->authTableCols['passwd']['type']); } else { // If only $handle is set, try to find the first matching user $sql = 'SELECT ' . implode(',', $fields) . ' FROM ' . $this->authTable . ' WHERE ' . $this->authTableCols['handle']['name'] . '=' . $this->dbc->quote($handle, $this->authTableCols['handle']['type']); } // Query database $result = $this->dbc->queryRow($sql, $types, MDB2_FETCHMODE_ASSOC); // If a user was found, read data into class variables and set // return value to true if (!MDB2::isError($result) && is_array($result)) { $this->handle = $result['handle']; $this->passwd = $this->decryptPW($result['passwd']); $this->isActive = !isset($result['is_active']) || $result['is_active'] ? true : false; $this->authUserId = $result['user_id']; $this->lastLogin = !empty($result['lastlogin']) ? MDB2_Date::mdbstamp2Unix($result['lastlogin']) : ''; $success = true; } return $success; }
/** * Inserts $message to the currently open database. Calls open(), * if necessary. Also passes the message along to any Log_observer * instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the connection isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* If we don't already have a statement object, create one. */ if (!is_object($this->_statement) && !$this->_prepareStatement()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); /* Build our set of values for this log entry. */ $values = array('id' => $this->_db->nextId($this->_sequence), 'logtime' => MDB2_Date::mdbNow(), 'ident' => $this->_ident, 'priority' => $priority, 'message' => $message); /* Execute the SQL query for this log entry insertion. */ $this->_db->expectError(MDB2_ERROR_NOSUCHTABLE); $result =& $this->_statement->execute($values); $this->_db->popExpect(); /* Attempt to handle any errors. */ if (PEAR::isError($result)) { /* We can only handle MDB2_ERROR_NOSUCHTABLE errors. */ if ($result->getCode() != MDB2_ERROR_NOSUCHTABLE) { return false; } /* Attempt to create the target table. */ if (!$this->_createTable()) { return false; } /* Recreate our prepared statement resource. */ $this->_statement->free(); if (!$this->_prepareStatement()) { return false; } /* Attempt to re-execute the insertion query. */ $result = $this->_statement->execute($values); if (PEAR::isError($result)) { return false; } } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; }
/** * Test replace query * * The replace method emulates the replace query of mysql * * @dataProvider provider */ public function testReplace($ci) { $this->manualSetUp($ci); if (!$this->supported('replace')) { $this->markTestSkipped('REPLACE not supported'); } $row = 1234; $data = $this->getSampleData($row); $fields = array('user_name' => array('value' => "user_{$row}", 'type' => 'text'), 'user_password' => array('value' => $data['user_password'], 'type' => 'text'), 'subscribed' => array('value' => $data['subscribed'], 'type' => 'boolean'), 'user_id' => array('value' => $data['user_id'], 'type' => 'integer', 'key' => 1), 'quota' => array('value' => $data['quota'], 'type' => 'decimal'), 'weight' => array('value' => $data['weight'], 'type' => 'float'), 'access_date' => array('value' => $data['access_date'], 'type' => 'date'), 'access_time' => array('value' => $data['access_time'], 'type' => 'time'), 'approved' => array('value' => $data['approved'], 'type' => 'timestamp')); $result = $this->db->replace($this->table_users, $fields); if (MDB2::isError($result)) { $this->fail('Replace failed'); } if ($this->db->supports('affected_rows')) { $this->assertEquals(1, $result, "replacing a row in an empty table returned incorrect value"); } $query = 'SELECT ' . implode(', ', array_keys($this->fields)) . ' FROM ' . $this->table_users; $result = $this->db->query($query, $this->fields); if (MDB2::isError($result)) { $this->fail('Error selecting from users' . $result->getUserInfo()); } $this->verifyFetchedValues($result, 0, $data); $row = 4321; $fields['user_name']['value'] = $data['user_name'] = 'user_' . $row; $fields['user_password']['value'] = $data['user_password'] = '******'; $fields['subscribed']['value'] = $data['subscribed'] = $row % 2 ? true : false; $fields['quota']['value'] = $data['quota'] = strval($row / 100); $fields['weight']['value'] = $data['weight'] = sqrt($row); $fields['access_date']['value'] = $data['access_date'] = MDB2_Date::mdbToday(); $fields['access_time']['value'] = $data['access_time'] = MDB2_Date::mdbTime(); $fields['approved']['value'] = $data['approved'] = MDB2_Date::mdbNow(); $result = $this->db->replace($this->table_users, $fields); if (MDB2::isError($result)) { $this->fail('Replace failed'); } if ($this->db->supports('affected_rows')) { switch ($this->db->phptype) { case 'sqlite': $expect = 1; break; default: $expect = 2; } $this->assertEquals($expect, $result, "replacing a row returned incorrect result"); } $query = 'SELECT ' . implode(', ', array_keys($this->fields)) . ' FROM ' . $this->table_users; $result = $this->db->query($query, $this->fields); if (MDB2::isError($result)) { $this->fail('Error selecting from users' . $result->getUserInfo()); } $this->verifyFetchedValues($result, 0, $data); $this->assertTrue(!$result->valid(), 'the query result did not seem to have reached the end of result as expected'); $result->free(); }
public function acquireLock($type = '') { if ($this->haveLock($type)) { return TRUE; } if (!$this->canAcquireLock()) { return FALSE; } $db =& $GLOBALS['db']; $sql = 'INSERT INTO db_object_lock (objectid, object_type, lock_type, userid, expires) VALUES ( ' . $db->quote($this->id) . ', ' . $db->quote(strtolower(get_class($this))) . ', ' . $db->quote($type) . ', ' . $db->quote($this->getCurrentUser('id')) . ', ' . $db->quote(MDB2_Date::unix2Mdbstamp(strtotime('+' . LOCK_LENGTH))) . ')'; $res = $db->query($sql); check_db_result($res); $this->_held_locks[$type] = TRUE; $this->_acquirable_locks[$type] = TRUE; if (rand(LOCK_CLEANUP_PROBABLILITY, 100) == 100) { $sql = 'DELETE FROM db_object_lock WHERE expires < ' . $db->quote(MDB2_Date::unix2Mdbstamp(time())); $res = $db->query($sql); check_db_result($res); } return TRUE; }
/** * Testing transaction support */ function testTransactions() { if (!$this->supported('transactions')) { return; } $this->db->autoCommit(0); $row = 0; $data = array(); $data['user_name'] = "user_{$row}"; $data['user_password'] = '******'; $data['subscribed'] = $row % 2 ? true : false; $data['user_id'] = $row; $data['quota'] = strval($row / 100); $data['weight'] = sqrt($row); $data['access_date'] = MDB2_Date::mdbToday(); $data['access_time'] = MDB2_Date::mdbTime(); $data['approved'] = MDB2_Date::mdbNow(); $prepared_query = $this->db->prepare('INSERT INTO users (user_name, user_password, subscribed, user_id, quota, weight, access_date, access_time, approved) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', $this->types); $this->insertTestValues($prepared_query, $data); $result = $this->db->execute($prepared_query); $this->db->rollback(); $result =& $this->db->query('SELECT * FROM users'); if (MDB2::isError($result)) { $this->assertTrue(false, 'Error selecting from users' . $result->getMessage()); } $this->assertTrue(!$result->valid(), 'Transaction rollback did not revert the row that was inserted'); $result->free(); $this->insertTestValues($prepared_query, $data); $result = $this->db->execute($prepared_query); $this->db->commit(); $result =& $this->db->query('SELECT * FROM users'); if (MDB2::isError($result)) { $this->assertTrue(false, 'Error selecting from users' . $result->getMessage()); } $this->assertTrue($result->valid(), 'Transaction commit did not make permanent the row that was inserted'); $result->free(); $result =& $this->db->query('DELETE FROM users'); if (MDB2::isError($result)) { $this->assertTrue(false, 'Error deleting from users' . $result->getMessage()); $this->db->rollback(); } $autocommit = $this->db->autocommit(1); $this->assertTrue(!MDB2::isError($autocommit), 'Error autocommiting transactions'); $this->db->freePrepared($prepared_query); $result =& $this->db->query('SELECT * FROM users'); if (MDB2::isError($result)) { $this->assertTrue(false, 'Error selecting from users' . $result->getMessage()); } $this->assertTrue(!$result->valid(), 'Transaction end with implicit commit when re-enabling auto-commit did not make permanent the rows that were deleted'); $result->free(); }
/** * @see http://pear.php.net/bugs/bug.php?id=670 */ function testBug670() { $data['user_name'] = null; $data['user_password'] = '******'; $data['subscribed'] = true; $data['user_id'] = 1; $data['quota'] = sprintf("%.2f", strval(3 / 100)); $data['weight'] = sqrt(1); $data['access_date'] = MDB2_Date::mdbToday(); $data['access_time'] = MDB2_Date::mdbTime(); $data['approved'] = MDB2_Date::mdbNow(); $stmt = $this->db->prepare('INSERT INTO users (' . implode(', ', array_keys($this->fields)) . ') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', array_values($this->fields), MDB2_PREPARE_MANIP); $result = $stmt->execute(array_values($data)); $result =& $this->db->query('SELECT user_name FROM users'); $col = $result->fetchCol('user_name'); if (PEAR::isError($col)) { $this->fail('Error when fetching column first first row as NULL: ' . $col->getMessage()); } $data['user_name'] = "user_1"; $data['user_id'] = 2; $result = $stmt->execute(array_values($data)); $result =& $this->db->query('SELECT user_name FROM users'); $col = $result->fetchCol('user_name'); if (PEAR::isError($col)) { $this->fail('Error when fetching column: ' . $col->getMessage()); } $data['user_name'] = null; $stmt->free(); }
function insertSessionDataToDatabase() { // Stores session data to database. $sql = "INSERT INTO ilmo_users (ilmo_id, id_string, confirmed, time) VALUES ({$this->newSignupid}, '{$this->sessionId}', 0, '" . MDB2_Date::mdbNow() . "')"; $this->database->doQuery($sql); }
<?php require_once "../DBInterface.php"; require_once "../ErrorReportEnabler.php"; MDB2::loadFile("Date"); $sql = "SELECT (" . MDB2_Date::mdbNow() . " - " . MDB2_Date::unix2Mdbstamp(strtotime('Jan 18, 2007')) . ")"; print "<p>{$sql}</p>"; $result = query($conn, $sql); print_r($result->fetchRow());
function timeToSql($timestamp) { return MDB2_Date::unix2Mdbstamp($timestamp); }
/** * http://pear.php.net/bugs/bug.php?id=3146 */ function testBug3146() { $data = array(); $total_rows = 5; $query = 'INSERT INTO users (' . implode(', ', array_keys($this->fields)) . ') VALUES (' . implode(', ', array_fill(0, count($this->fields), '?')) . ')'; $stmt = $this->db->prepare($query, array_values($this->fields), MDB2_PREPARE_MANIP); for ($row = 0; $row < $total_rows; $row++) { $data[$row]['user_name'] = "user_{$row}"; $data[$row]['user_password'] = '******'; $data[$row]['subscribed'] = (bool) ($row % 2); $data[$row]['user_id'] = $row; $data[$row]['quota'] = sprintf("%.2f", strval(1 + ($row + 1) / 100)); $data[$row]['weight'] = sqrt($row); $data[$row]['access_date'] = MDB2_Date::mdbToday(); $data[$row]['access_time'] = MDB2_Date::mdbTime(); $data[$row]['approved'] = MDB2_Date::mdbNow(); $result = $stmt->execute(array_values($data[$row])); if (PEAR::isError($result)) { $this->assertTrue(false, 'Error executing prepared query' . $result->getMessage()); } } $stmt->free(); $query = 'SELECT ' . implode(', ', array_keys($this->fields)) . ' FROM users ORDER BY user_id'; $result =& $this->db->query($query, $this->fields); $numrows = $result->numRows($result); $this->verifyFetchedValues($result, 0, $data[0]); $this->verifyFetchedValues($result, 2, $data[2]); $this->verifyFetchedValues($result, null, $data[3]); $this->verifyFetchedValues($result, 1, $data[1]); $result->free(); }
/** * Reads auth_user_id, passwd, is_active flag * lastlogin timestamp from the database * If only $handle is given, it will read the data * from the first user with that handle and return * true on success. * If $handle and $passwd are given, it will try to * find the first user with both handle and password * matching and return true on success (this allows * multiple users having the same handle but different * passwords - yep, some people want this). * If no match is found, false is being returned. * * @param string $handle user handle * @param boolean $passwd user password * @param string $auth_user_id auth user id * @return boolean true on success or false on failure * * @access private */ function readUserData($handle = '', $passwd = '', $auth_user_id = false) { $fields = $types = array(); foreach ($this->tables['users']['fields'] as $field => $req) { $fields[] = $this->alias[$field] . ' AS ' . $field; $types[] = $this->fields[$field]; } // Setting the default query. $query = 'SELECT ' . implode(',', $fields) . ' FROM ' . $this->prefix . $this->alias['users'] . ' WHERE '; if ($auth_user_id) { $query .= $this->alias['auth_user_id'] . '=' . $this->dbc->quote($this->propertyValues['auth_user_id'], $this->fields['auth_user_id']); } else { $query .= $this->alias['handle'] . '=' . $this->dbc->quote($handle, $this->fields['handle']); if ($this->tables['users']['fields']['passwd']) { // If $passwd is set, try to find the first user with the given // handle and password. $query .= ' AND ' . $this->alias['passwd'] . '=' . $this->dbc->quote($this->encryptPW($passwd), $this->fields['passwd']); } } // Query database $result = $this->dbc->queryRow($query, $types, MDB2_FETCHMODE_ASSOC); // If a user was found, read data into class variables and set // return value to true if (PEAR::isError($result)) { $this->_stack->push(LIVEUSER_ERROR, 'exception', array('reason' => $result->getMessage() . '-' . $result->getUserInfo())); return false; } if (!is_array($result)) { return null; } if (array_key_exists('lastlogin', $result) && !empty($result['lastlogin'])) { $result['lastlogin'] = MDB2_Date::mdbstamp2Unix($result['lastlogin']); } $this->propertyValues = $result; return true; }
// since we are on php5 we can use the magic __call() method to: // - load the manager module: $mdb2->loadModule('Manager', null, true); // - redirect the method call to the manager module: $mdb2->manager->createTable('sometable', $fields); $mdb2->mgCreateTable($table, $fields); $query = "INSERT INTO {$table} (somename, somedate) VALUES (:name, :date)"; // parameters: // 1) the query (notice we are using named parameters, but we could also use ? instead // 2) types of the placeholders (either keyed numerically in order or by name) // 3) MDB2_PREPARE_MANIP denotes a DML statement $stmt = $mdb2->prepare($query, array('text', 'date'), MDB2_PREPARE_MANIP); if (PEAR::isError($stmt)) { die($stmt->getMessage()); } // load Date helper class MDB2::loadFile('Date'); $stmt->execute(array('name' => 'hello', 'date' => MDB2_Date::mdbToday())); // get the last inserted id echo 'last insert id: '; var_dump($mdb2->lastInsertId($table, 'id')); $stmt->execute(array('name' => 'world', 'date' => '2005-11-11')); // get the last inserted id echo 'last insert id: '; var_dump($mdb2->lastInsertId($table, 'id')); // load Iterator implementations MDB2::loadFile('Iterator'); $query = 'SELECT * FROM ' . $table; // parameters: // 1) the query // 2) true means MDB2 tries to determine the result set type automatically // 3) true is the default and means that internally a MDB2_Result instance should be created // 4) 'MDB2_BufferedIterator' means the MDB2_Result should be wrapped inside an SeekableIterator
/** * Return string to call a variable with the current timestamp inside an SQL statement * There are three special variables for current date and time: * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type) * - CURRENT_DATE (date, DATE type) * - CURRENT_TIME (time, TIME type) * * @return string to call a variable with the current timestamp * @access public */ public function now() { if ($this->dbLayer === 'MDB2') { return MDB2_Date::mdbNow(); } elseif ($this->dbLayer === 'PDO') { return date('Y-m-d H:i:s'); } }