diff --git a/lib/ControlPanel.php b/lib/ControlPanel.php
index ade739b30..9d02f201b 100755
--- a/lib/ControlPanel.php
+++ b/lib/ControlPanel.php
@@ -145,9 +145,9 @@ public function getDeleteRow()
$uIDName = $this->getPostValue('uIDName');
$sql = $this->getTablesSQL(sprintf('%s = %d', addslashes($uIDName), addslashes($uID)));
$rs = $this->_db->query($sql);
- if ($rs && mysqli_num_rows($rs) > 0)
+ if ($rs && $this->_db->getNumRows() > 0)
{
- $row = mysqli_fetch_array($rs, MYSQLI_ASSOC);
+ $row = $this->_db->getAssoc();
if (!$row)
{
return $this->getException('Bad or expired identifier', 'The operation you attempted cannot complete '
@@ -206,7 +206,7 @@ public function getWebForm($addRecord = false)
. 'because the unique identifier no longer exists. Did you perhaps use your browser\'s back '
. 'button?');
}
- $row = mysqli_fetch_array($rs, MYSQLI_ASSOC);
+ $row = $this->_db->getAssoc();
if (!$row)
{
return $this->getListView();
@@ -415,9 +415,9 @@ public function getWebForm($addRecord = false)
}
else
{
- $updatedRows += mysqli_affected_rows($this->_db->getConnection());
+ $updatedRows += $this->_db->getAffectedRows();
if ($addRecord && $callBackPrimaryKey)
- $row[$callBackPrimaryKey] = mysqli_insert_id($this->_db->getConnection());
+ $row[$callBackPrimaryKey] = $this->_db->getLastInsertID();
if ($callBack)
$callBack($row);
}
@@ -814,7 +814,7 @@ public function getListView()
if ($currencySql != '')
{
$rs = $this->_db->query($sql = $this->getTablesSQL($searchSql, '', $currencySql));
- $currencySums = mysqli_fetch_array($rs, MYSQLI_ASSOC);
+ $currencySums = $this->_db->getAssoc();
}
}
@@ -833,8 +833,9 @@ public function getListView()
$pager_CurrentPage = intval($pager_CurrentPage) - 1;
// get the records count
- $rs = $this->_db->query($sql = $this->getTablesSQL($searchSql, '', 'COUNT(*)'));
- $rsCount = intval(mysqli_fetch_row($rs));
+ $rs = $this->_db->query($sql = $this->getTablesSQL($searchSql, '', 'COUNT(*) AS cpRecordCount'));
+ $countRow = $this->_db->getAssoc();
+ $rsCount = intval($countRow['cpRecordCount'] ?? 0);
$numPages = ceil($rsCount / $pager_ResultsPerPage);
if ($pager_CurrentPage >= $numPages) $pager_CurrentPage = $numPages - 1;
if ($pager_CurrentPage < 0) $pager_CurrentPage = 0;
@@ -859,7 +860,7 @@ public function getListView()
$fieldOffset = true;
$rowNum = 0;
- while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC))
+ while (($row = $this->_db->getAssoc()))
{
$numColumns = 0;
$infoHtml .= "
\n";
@@ -1443,7 +1444,7 @@ public function addMySQLTable($name)
$this->_tables[$name]['fields'] = array();
// Fetch the fields from the table
$rs = $this->_db->query('SHOW FIELDS FROM ' . $name);
- while ($row = mysqli_fetch_array($rs, MYSQLI_ASSOC))
+ while (($row = $this->_db->getAssoc()))
{
$this->_tables[$name]['fields'][$row['Field']] = array(
'type' => $row['Type'],
diff --git a/lib/DatabaseConnection.php b/lib/DatabaseConnection.php
index fcd6f3814..a19f3c638 100755
--- a/lib/DatabaseConnection.php
+++ b/lib/DatabaseConnection.php
@@ -287,7 +287,7 @@ public function getColumn($query = null, $row, $column)
/**
* Returns one row from a query's result set in an associative array,
* starting at the current row pointer. After the call, the row pointer
- * will be incemented by 1 (this is how the mysql_fetch_*() functions
+ * will be incremented by 1 (this matches mysqli_fetch_*() behavior
* work). If a query is not specified, this method will operate on the
* last executed query for this instance. Specifing a query always resets
* the row pointer to 0.
@@ -575,7 +575,7 @@ public function makeQueryDouble($value, $precision = false)
}
/**
- * Returns the last error message (value of mysql_error()) for the current
+ * Returns the last connection error message for the current
* MySQL connection.
*
* @return string Error message, or '' if no error occurred.
diff --git a/modules/install/OptionalComponents.php b/modules/install/OptionalComponents.php
index bcaf511f2..ab5bfab76 100755
--- a/modules/install/OptionalComponents.php
+++ b/modules/install/OptionalComponents.php
@@ -39,9 +39,9 @@
CATSUtility::changeConfigSetting(\'US_ZIPS_ENABLED\', "false");
';
$optionalComponents['usZipCodes']['detectCode'] = '
- $rs = MySQLQuery(\'SELECT * FROM zipcodes\');
+ $recordSet = MySQLGetAssoc(\'SELECT zipcode FROM zipcodes LIMIT 1\');
- if ($rs && mysqli_fetch_row($rs))
+ if (!empty($recordSet))
{
return true;
}
diff --git a/modules/install/Schema.php b/modules/install/Schema.php
index 5562d4ccf..7a04a68b8 100755
--- a/modules/install/Schema.php
+++ b/modules/install/Schema.php
@@ -722,7 +722,7 @@ public static function get()
"UPDATE
dashboard_component
SET
- module_parameters = \'" . mysql_real_escape_string($serializedValue) . "\'
+ module_parameters = " . $db->makeQueryString($serializedValue) . "
WHERE
dashboard_component_id = " . $row[\'dashboard_component_id\']
);
@@ -849,9 +849,9 @@ public static function get()
UPDATE system SET disable_version_check = 1;
',
'253' => 'PHP:
- $rs = $db->query(\'SELECT * FROM zipcodes\');
+ $rs = $db->getAssoc(\'SELECT zipcode FROM zipcodes LIMIT 1\');
- if ($rs && mysql_fetch_row($rs))
+ if (!empty($rs))
{
$db->query(\'DELETE FROM zipcodes\');
$schemaZipcodes = @file_get_contents(\'db/upgrade-zipcodes.sql\');
@@ -1233,7 +1233,7 @@ public static function get()
$lists = $db->getAllAssoc("SELECT * FROM saved_list");
foreach($lists as $list)
{
- $db->query(sprintf("UPDATE saved_list SET description = \"%s\" WHERE saved_list_id = %s", mysql_real_escape_string(urldecode($list[\'description\'])), $list[\'saved_list_id\']));
+ $db->query(sprintf("UPDATE saved_list SET description = %s WHERE saved_list_id = %s", $db->makeQueryString(urldecode($list[\'description\'])), $list[\'saved_list_id\']));
}
',
'343' => '
diff --git a/modules/install/ajax/ui.php b/modules/install/ajax/ui.php
index cc601d92f..1278d841d 100755
--- a/modules/install/ajax/ui.php
+++ b/modules/install/ajax/ui.php
@@ -182,9 +182,11 @@
$mailFromAddress = '';
if (isset($tables['settings']))
{
- $rs = MySQLQuery('SELECT value FROM settings WHERE setting = "fromAddress" LIMIT 1');
- if (mysqli_num_rows($rs) > 0)
- $mailFromAddress = mysqli_fetch_row($rs);
+ $recordSet = MySQLGetAssoc('SELECT value FROM settings WHERE setting = "fromAddress" LIMIT 1');
+ if (!empty($recordSet))
+ {
+ $mailFromAddress = array($recordSet['value']);
+ }
}
echo '
@@ -473,15 +475,7 @@
echo '';
@@ -1112,7 +1109,7 @@
function MySQLConnect()
{
- global $tables, $mySQLConnection;
+ global $tables, $mySQLConnection, $db;
$mySQLConnection = @mysqli_connect(
DATABASE_HOST, DATABASE_USER, DATABASE_PASS
@@ -1132,12 +1129,16 @@ function MySQLConnect()
}
+ include_once(LEGACY_ROOT . '/lib/DatabaseConnection.php');
+ $db = DatabaseConnection::getInstance();
+
/* Create an array of all tables in the database. */
$tables = array();
- $result = MySQLQuery(sprintf("SHOW TABLES FROM `%s`", DATABASE_NAME));
- while ($row = mysqli_fetch_row($result))
+ $resultSet = MySQLGetAllAssoc(sprintf("SHOW TABLES FROM `%s`", DATABASE_NAME));
+ foreach ($resultSet as $row)
{
- $tables[$row[0]] = true;
+ $tableName = reset($row);
+ $tables[$tableName] = true;
}
/* Select CATS database. */
@@ -1179,6 +1180,30 @@ function MySQLQuery($query, $ignoreErrors = false)
return $queryResult;
}
+function MySQLGetAssoc($query, $ignoreErrors = false)
+{
+ global $db;
+
+ if (!$db->query($query, $ignoreErrors))
+ {
+ return array();
+ }
+
+ return $db->getAssoc();
+}
+
+function MySQLGetAllAssoc($query, $ignoreErrors = false)
+{
+ global $db;
+
+ if (!$db->query($query, $ignoreErrors))
+ {
+ return array();
+ }
+
+ return $db->getAllAssoc();
+}
+
function MySQLQueryMultiple($SQLData, $delimiter = ';')
{
$SQLStatments = explode($delimiter, $SQLData);
diff --git a/modules/install/backupDB.php b/modules/install/backupDB.php
index 6a7d02acc..80e94ce27 100755
--- a/modules/install/backupDB.php
+++ b/modules/install/backupDB.php
@@ -75,16 +75,12 @@ function dumpDB($db, $file, $useStatus = false, $splitFiles = true, $siteID = -1
$len = 0;
$fileNumber = 0;
- $connection = $db->getConnection();
-
$text = '';
- $result = mysqli_query($connection,
- sprintf("SHOW TABLES FROM `%s`", DATABASE_NAME)
- );
- while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
+ $resultSet = $db->getAllAssoc(sprintf("SHOW TABLES FROM `%s`", DATABASE_NAME));
+ foreach ($resultSet as $row)
{
- $tables[] = $row[0];
+ $tables[] = reset($row);
}
if ($splitFiles) $fh = fopen($file . '.' . $fileNumber, 'w');
@@ -107,13 +103,10 @@ function dumpDB($db, $file, $useStatus = false, $splitFiles = true, $siteID = -1
$text .= 'DROP TABLE IF EXISTS `' . $table . '`((ENDOFQUERY))'."\n";
$sql = 'SHOW CREATE TABLE ' . $table;
- $rs = mysqli_query($connection, $sql);
- if ($rs)
+ $row = $db->getAssoc($sql);
+ if (!empty($row))
{
- if ($row = mysqli_fetch_assoc($rs))
- {
- $text .= $row['Create Table'] . "((ENDOFQUERY))\n\n";
- }
+ $text .= $row['Create Table'] . "((ENDOFQUERY))\n\n";
}
if ($table == 'word_verification') continue;
@@ -131,14 +124,14 @@ function dumpDB($db, $file, $useStatus = false, $splitFiles = true, $siteID = -1
$isSiteIdColumn = false;
$sql = sprintf("SHOW COLUMNS FROM %s", $table);
- $rs = mysqli_query($connection, $sql);
- while ($recordSet = mysqli_fetch_assoc($rs))
+ $columnRecordSet = $db->getAllAssoc($sql);
+ foreach ($columnRecordSet as $recordSet)
{
if ($recordSet['Field'] == 'site_id')
{
$isSiteIdColumn = true;
}
- }
+ }
if ($isSiteIdColumn)
{
@@ -149,9 +142,9 @@ function dumpDB($db, $file, $useStatus = false, $splitFiles = true, $siteID = -1
$sql = 'SELECT * FROM ' . $table . '';
}
- $rs = mysqli_query($sql, $connection);
$index = 0;
- while ($recordSet = mysqli_fetch_assoc($rs))
+ $tableRecordSet = $db->getAllAssoc($sql);
+ foreach ($tableRecordSet as $recordSet)
{
$continue = true;
@@ -227,7 +220,7 @@ function dumpDB($db, $file, $useStatus = false, $splitFiles = true, $siteID = -1
$i = 0;
foreach ($recordSet as $field)
{
- $text .= "'".mysqli_real_escape_string($connection, $field)."'";
+ $text .= $db->makeQueryString($field);
$i++;
if ($i != count($recordSet))
{
diff --git a/modules/settings/ajax/backup.php b/modules/settings/ajax/backup.php
index 127fd2191..ab5dee493 100755
--- a/modules/settings/ajax/backup.php
+++ b/modules/settings/ajax/backup.php
@@ -245,13 +245,19 @@ function setStatusBackup($status, $progress)
site_id = %s",
$siteID
);
- $queryResult = mysqli_query($db, $sql);
- $totalAttachments = mysqli_num_rows($queryResult);
+ $db->query($sql);
+ $totalAttachments = $db->getNumRows();
/* Add each attachment to the zip file. */
$attachmentCount = 0;
- while ($row = mysqli_fetch_assoc($queryResult))
+ while (true)
{
+ $row = $db->getAssoc();
+ if (empty($row))
+ {
+ break;
+ }
+
++$attachmentCount;
$relativePath = sprintf(
'attachments/%s/%s',
diff --git a/rebuild_old_docs.php b/rebuild_old_docs.php
index 8ee297939..74c9066a3 100644
--- a/rebuild_old_docs.php
+++ b/rebuild_old_docs.php
@@ -52,7 +52,6 @@ function rebuild_old_docs() {
}
-//$con = mysql_connect("localhost","root","root");
$con = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASS);
if (!$con)
{
diff --git a/scripts/makeBackup.php b/scripts/makeBackup.php
index dea8c4a7a..33a6bafb2 100755
--- a/scripts/makeBackup.php
+++ b/scripts/makeBackup.php
@@ -243,12 +243,18 @@ function dumpAttachments($db, $directory, $siteID)
$siteID
);
- $queryResult = mysqli_query($db, $sql);
- $totalAttachments = mysqli_num_rows($queryResult);
+ $db->query($sql);
+ $totalAttachments = $db->getNumRows();
/* Add each attachment to the zip file. */
- while ($row = mysqli_fetch_assoc($queryResult))
+ while (true)
{
+ $row = $db->getAssoc();
+ if (empty($row))
+ {
+ break;
+ }
+
$relativePath = sprintf(
'attachments/%s/%s',
$row['directory_name'],
diff --git a/src/OpenCATS/Tests/IntegrationTests/DatabaseConnectionTest.php b/src/OpenCATS/Tests/IntegrationTests/DatabaseConnectionTest.php
index 7227efe9d..ca079b452 100644
--- a/src/OpenCATS/Tests/IntegrationTests/DatabaseConnectionTest.php
+++ b/src/OpenCATS/Tests/IntegrationTests/DatabaseConnectionTest.php
@@ -196,6 +196,121 @@ function testQuery()
'DELETE query should succeed'
);
}
+
+ function testGetAssocWithoutQueryUsesActiveResultSetAndAdvances()
+ {
+ $db = DatabaseConnection::getInstance();
+
+ $db->query('INSERT INTO installtest (id) VALUES (101), (102)');
+ $db->query('SELECT id FROM installtest ORDER BY id ASC');
+
+ $firstRow = $db->getAssoc();
+ $secondRow = $db->getAssoc();
+ $thirdRow = $db->getAssoc();
+
+ $this->assertSame(
+ array('id' => '101'),
+ $firstRow,
+ 'First row should be returned from the active result set.'
+ );
+ $this->assertSame(
+ array('id' => '102'),
+ $secondRow,
+ 'Second call should advance to the next row in the active result set.'
+ );
+ $this->assertSame(
+ array(),
+ $thirdRow,
+ 'Exhausted active result sets should return an empty array.'
+ );
+ }
+
+ function testGetAssocWithoutQuerySupportsCountRowAfterQuery()
+ {
+ $db = DatabaseConnection::getInstance();
+
+ $db->query('INSERT INTO installtest (id) VALUES (201), (202), (203)');
+ $db->query('SELECT COUNT(*) AS totalRows FROM installtest');
+
+ $countRow = $db->getAssoc();
+
+ $this->assertSame(
+ array('totalRows' => '3'),
+ $countRow,
+ 'No-argument getAssoc() should read the count-like row from the active result set.'
+ );
+ }
+
+ function testGetNumRowsReturnsRowCountForActiveSelectResult()
+ {
+ $db = DatabaseConnection::getInstance();
+
+ $db->query('INSERT INTO installtest (id) VALUES (301), (302), (303)');
+ $db->query('SELECT id FROM installtest ORDER BY id ASC');
+
+ $this->assertSame(
+ 3,
+ $db->getNumRows(),
+ 'getNumRows() should return row count from the active SELECT result set.'
+ );
+ }
+
+ function testGetAffectedRowsReflectsInsertUpdateAndDelete()
+ {
+ $db = DatabaseConnection::getInstance();
+
+ $db->query('INSERT INTO installtest (id) VALUES (401), (402)');
+ $this->assertSame(
+ 2,
+ $db->getAffectedRows(),
+ 'getAffectedRows() should return inserted row count.'
+ );
+
+ $db->query('UPDATE installtest SET id = id + 1000 WHERE id IN (401, 402)');
+ $this->assertSame(
+ 2,
+ $db->getAffectedRows(),
+ 'getAffectedRows() should return updated row count.'
+ );
+
+ $db->query('DELETE FROM installtest WHERE id IN (1401, 1402)');
+ $this->assertSame(
+ 2,
+ $db->getAffectedRows(),
+ 'getAffectedRows() should return deleted row count.'
+ );
+ }
+
+ function testGetLastInsertIDReturnsAutoIncrementValue()
+ {
+ $db = DatabaseConnection::getInstance();
+
+ $db->query(
+ 'CREATE TABLE test_autoincrement ('
+ . 'id INT NOT NULL AUTO_INCREMENT, '
+ . 'label VARCHAR(32) NOT NULL, '
+ . 'PRIMARY KEY (id)'
+ . ') ENGINE=InnoDB DEFAULT CHARSET=utf8'
+ );
+
+ $db->query("INSERT INTO test_autoincrement (label) VALUES ('first row')");
+ $firstInsertId = $db->getLastInsertID();
+
+ $db->query("INSERT INTO test_autoincrement (label) VALUES ('second row')");
+ $secondInsertId = $db->getLastInsertID();
+
+ $this->assertSame(
+ 1,
+ (int) $firstInsertId,
+ 'First insert should return auto-increment ID 1.'
+ );
+ $this->assertSame(
+ 2,
+ (int) $secondInsertId,
+ 'Second insert should return auto-increment ID 2.'
+ );
+ }
+
}
?>