PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/mysql.class.php

https://bitbucket.org/PapayaMedia/diplomado
PHP | 1801 lines | 1208 code | 82 blank | 511 comment | 289 complexity | c0d5f4a0b18914714de73168c15ac4ed MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Ultimate MySQL Wrapper Class
  4. *
  5. * @version 2.5.1
  6. * @author Jeff L. Williams
  7. * @link http://www.phpclasses.org/ultimatemysql
  8. *
  9. * Contributions from
  10. * Frank P. Walentynowicz
  11. * Larry Wakeman
  12. * Nicola Abbiuso
  13. * Douglas Gintz
  14. * Emre Erkan
  15. * Vincent van Daal
  16. */
  17. class MySQL
  18. {
  19. // SET THESE VALUES TO MATCH YOUR DATA CONNECTION
  20. private $db_host = "localhost"; // server name
  21. private $db_user = ""; // user name
  22. private $db_pass = ""; // password
  23. private $db_dbname = ""; // database name
  24. private $db_charset = ""; // optional character set (i.e. utf8)
  25. private $db_pcon = false; // use persistent connection?
  26. // constants for SQLValue function
  27. const SQLVALUE_BIT = "bit";
  28. const SQLVALUE_BOOLEAN = "boolean";
  29. const SQLVALUE_DATE = "date";
  30. const SQLVALUE_DATETIME = "datetime";
  31. const SQLVALUE_NUMBER = "number";
  32. const SQLVALUE_T_F = "t-f";
  33. const SQLVALUE_TEXT = "text";
  34. const SQLVALUE_TIME = "time";
  35. const SQLVALUE_Y_N = "y-n";
  36. // class-internal variables - do not change
  37. private $active_row = -1; // current row
  38. private $error_desc = ""; // last mysql error string
  39. private $error_number = 0; // last mysql error number
  40. private $in_transaction = false; // used for transactions
  41. private $last_insert_id; // last id of record inserted
  42. private $last_result; // last mysql query result
  43. private $last_sql = ""; // last mysql query
  44. private $mysql_link = 0; // mysql link resource
  45. private $time_diff = 0; // holds the difference in time
  46. private $time_start = 0; // start time for the timer
  47. /**
  48. * Determines if an error throws an exception
  49. *
  50. * @var boolean Set to true to throw error exceptions
  51. */
  52. public $ThrowExceptions = false;
  53. /**
  54. * Constructor: Opens the connection to the database
  55. *
  56. * @param boolean $connect (Optional) Auto-connect when object is created
  57. * @param string $database (Optional) Database name
  58. * @param string $server (Optional) Host address
  59. * @param string $username (Optional) User name
  60. * @param string $password (Optional) Password
  61. * @param string $charset (Optional) Character set
  62. */
  63. public function __construct($connect = true, $database = null, $server = null,
  64. $username = null, $password = null, $charset = null) {
  65. if ($database !== null) $this->db_dbname = $database;
  66. if ($server !== null) $this->db_host = $server;
  67. if ($username !== null) $this->db_user = $username;
  68. if ($password !== null) $this->db_pass = $password;
  69. if ($charset !== null) $this->db_charset = $charset;
  70. if (strlen($this->db_host) > 0 &&
  71. strlen($this->db_user) > 0) {
  72. if ($connect) $this->Open();
  73. }
  74. }
  75. /**
  76. * Destructor: Closes the connection to the database
  77. *
  78. */
  79. public function __destruct() {
  80. $this->Close();
  81. }
  82. /**
  83. * Automatically does an INSERT or UPDATE depending if an existing record
  84. * exists in a table
  85. *
  86. * @param string $tableName The name of the table
  87. * @param array $valuesArray An associative array containing the column
  88. * names as keys and values as data. The values
  89. * must be SQL ready (i.e. quotes around
  90. * strings, formatted dates, ect)
  91. * @param array $whereArray An associative array containing the column
  92. * names as keys and values as data. The values
  93. * must be SQL ready (i.e. quotes around strings,
  94. * formatted dates, ect).
  95. * @return boolean Returns TRUE on success or FALSE on error
  96. */
  97. public function AutoInsertUpdate($tableName, $valuesArray, $whereArray) {
  98. $this->ResetError();
  99. $this->SelectRows($tableName, $whereArray);
  100. if (! $this->Error()) {
  101. if ($this->HasRecords()) {
  102. return $this->UpdateRows($tableName, $valuesArray, $whereArray);
  103. } else {
  104. return $this->InsertRow($tableName, $valuesArray);
  105. }
  106. } else {
  107. return false;
  108. }
  109. }
  110. /**
  111. * Returns true if the internal pointer is at the beginning of the records
  112. *
  113. * @return boolean TRUE if at the first row or FALSE if not
  114. */
  115. public function BeginningOfSeek() {
  116. $this->ResetError();
  117. if ($this->IsConnected()) {
  118. if ($this->active_row < 1) {
  119. return true;
  120. } else {
  121. return false;
  122. }
  123. } else {
  124. $this->SetError("No connection");
  125. return false;
  126. }
  127. }
  128. /**
  129. * [STATIC] Builds a comma delimited list of columns for use with SQL
  130. *
  131. * @param array $valuesArray An array containing the column names.
  132. * @param boolean $addQuotes (Optional) TRUE to add quotes
  133. * @param boolean $showAlias (Optional) TRUE to show column alias
  134. * @return string Returns the SQL column list
  135. */
  136. static private function BuildSQLColumns($columns, $addQuotes = true, $showAlias = true) {
  137. if ($addQuotes) {
  138. $quote = "`";
  139. } else {
  140. $quote = "";
  141. }
  142. switch (gettype($columns)) {
  143. case "array":
  144. $sql = "";
  145. foreach ($columns as $key => $value) {
  146. // Build the columns
  147. if (strlen($sql) == 0) {
  148. $sql = $quote . $value . $quote;
  149. } else {
  150. $sql .= ", " . $quote . $value . $quote;
  151. }
  152. if ($showAlias && is_string($key) && (! empty($key))) {
  153. $sql .= ' AS "' . $key . '"';
  154. }
  155. }
  156. return $sql;
  157. break;
  158. case "string":
  159. return $quote . $columns . $quote;
  160. break;
  161. default:
  162. return false;
  163. break;
  164. }
  165. }
  166. /**
  167. * [STATIC] Builds a SQL DELETE statement
  168. *
  169. * @param string $tableName The name of the table
  170. * @param array $whereArray (Optional) An associative array containing the
  171. * column names as keys and values as data. The
  172. * values must be SQL ready (i.e. quotes around
  173. * strings, formatted dates, ect). If not specified
  174. * then all values in the table are deleted.
  175. * @return string Returns the SQL DELETE statement
  176. */
  177. static public function BuildSQLDelete($tableName, $whereArray = null) {
  178. $sql = "DELETE FROM `" . $tableName . "`";
  179. if (! is_null($whereArray)) {
  180. $sql .= self::BuildSQLWhereClause($whereArray);
  181. }
  182. return $sql;
  183. }
  184. /**
  185. * [STATIC] Builds a SQL INSERT statement
  186. *
  187. * @param string $tableName The name of the table
  188. * @param array $valuesArray An associative array containing the column
  189. * names as keys and values as data. The values
  190. * must be SQL ready (i.e. quotes around
  191. * strings, formatted dates, ect)
  192. * @return string Returns a SQL INSERT statement
  193. */
  194. static public function BuildSQLInsert($tableName, $valuesArray) {
  195. $columns = self::BuildSQLColumns(array_keys($valuesArray));
  196. $values = self::BuildSQLColumns($valuesArray, false, false);
  197. $sql = "INSERT INTO `" . $tableName .
  198. "` (" . $columns . ") VALUES (" . $values . ")";
  199. return $sql;
  200. }
  201. /**
  202. * Builds a simple SQL SELECT statement
  203. *
  204. * @param string $tableName The name of the table
  205. * @param array $whereArray (Optional) An associative array containing the
  206. * column names as keys and values as data. The
  207. * values must be SQL ready (i.e. quotes around
  208. * strings, formatted dates, ect)
  209. * @param array/string $columns (Optional) The column or list of columns to select
  210. * @param array/string $sortColumns (Optional) Column or list of columns to sort by
  211. * @param boolean $sortAscending (Optional) TRUE for ascending; FALSE for descending
  212. * This only works if $sortColumns are specified
  213. * @param integer/string $limit (Optional) The limit of rows to return
  214. * @return string Returns a SQL SELECT statement
  215. */
  216. static public function BuildSQLSelect($tableName, $whereArray = null, $columns = null,
  217. $sortColumns = null, $sortAscending = true, $limit = null) {
  218. if (! is_null($columns)) {
  219. $sql = self::BuildSQLColumns($columns);
  220. } else {
  221. $sql = "*";
  222. }
  223. $sql = "SELECT " . $sql . " FROM `" . $tableName . "`";
  224. if (is_array($whereArray)) {
  225. $sql .= self::BuildSQLWhereClause($whereArray);
  226. }
  227. if (! is_null($sortColumns)) {
  228. $sql .= " ORDER BY " .
  229. self::BuildSQLColumns($sortColumns, true, false) .
  230. " " . ($sortAscending ? "ASC" : "DESC");
  231. }
  232. if (! is_null($limit)) {
  233. $sql .= " LIMIT " . $limit;
  234. }
  235. return $sql;
  236. }
  237. /**
  238. * [STATIC] Builds a SQL UPDATE statement
  239. *
  240. * @param string $tableName The name of the table
  241. * @param array $valuesArray An associative array containing the column
  242. * names as keys and values as data. The values
  243. * must be SQL ready (i.e. quotes around
  244. * strings, formatted dates, ect)
  245. * @param array $whereArray (Optional) An associative array containing the
  246. * column names as keys and values as data. The
  247. * values must be SQL ready (i.e. quotes around
  248. * strings, formatted dates, ect). If not specified
  249. * then all values in the table are updated.
  250. * @return string Returns a SQL UPDATE statement
  251. */
  252. static public function BuildSQLUpdate($tableName, $valuesArray, $whereArray = null) {
  253. $sql = "";
  254. foreach ($valuesArray as $key => $value) {
  255. if (strlen($sql) == 0) {
  256. $sql = "`" . $key . "` = " . $value;
  257. } else {
  258. $sql .= ", `" . $key . "` = " . $value;
  259. }
  260. }
  261. $sql = "UPDATE `" . $tableName . "` SET " . $sql;
  262. if (is_array($whereArray)) {
  263. $sql .= self::BuildSQLWhereClause($whereArray);
  264. }
  265. return $sql;
  266. }
  267. /**
  268. * [STATIC] Builds a SQL WHERE clause from an array.
  269. * If a key is specified, the key is used at the field name and the value
  270. * as a comparison. If a key is not used, the value is used as the clause.
  271. *
  272. * @param array $whereArray An associative array containing the column
  273. * names as keys and values as data. The values
  274. * must be SQL ready (i.e. quotes around
  275. * strings, formatted dates, ect)
  276. * @return string Returns a string containing the SQL WHERE clause
  277. */
  278. static public function BuildSQLWhereClause($whereArray) {
  279. $where = "";
  280. foreach ($whereArray as $key => $value) {
  281. if (strlen($where) == 0) {
  282. if (is_string($key)) {
  283. $where = " WHERE `" . $key . "` = " . $value;
  284. } else {
  285. $where = " WHERE " . $value;
  286. }
  287. } else {
  288. if (is_string($key)) {
  289. $where .= " AND `" . $key . "` = " . $value;
  290. } else {
  291. $where .= " AND " . $value;
  292. }
  293. }
  294. }
  295. return $where;
  296. }
  297. /**
  298. * Close current MySQL connection
  299. *
  300. * @return object Returns TRUE on success or FALSE on error
  301. */
  302. public function Close() {
  303. $this->ResetError();
  304. $this->active_row = -1;
  305. $success = $this->Release();
  306. if ($success) {
  307. $success = @mysql_close($this->mysql_link);
  308. if (! $success) {
  309. $this->SetError();
  310. } else {
  311. unset($this->last_sql);
  312. unset($this->last_result);
  313. unset($this->mysql_link);
  314. }
  315. }
  316. return $success;
  317. }
  318. /**
  319. * Deletes rows in a table based on a WHERE filter
  320. * (can be just one or many rows based on the filter)
  321. *
  322. * @param string $tableName The name of the table
  323. * @param array $whereArray (Optional) An associative array containing the
  324. * column names as keys and values as data. The
  325. * values must be SQL ready (i.e. quotes around
  326. * strings, formatted dates, ect). If not specified
  327. * then all values in the table are deleted.
  328. * @return boolean Returns TRUE on success or FALSE on error
  329. */
  330. public function DeleteRows($tableName, $whereArray = null) {
  331. $this->ResetError();
  332. if (! $this->IsConnected()) {
  333. $this->SetError("No connection");
  334. return false;
  335. } else {
  336. $sql = self::BuildSQLDelete($tableName, $whereArray);
  337. // Execute the UPDATE
  338. if (! $this->Query($sql)) {
  339. return false;
  340. } else {
  341. return true;
  342. }
  343. }
  344. }
  345. /**
  346. * Returns true if the internal pointer is at the end of the records
  347. *
  348. * @return boolean TRUE if at the last row or FALSE if not
  349. */
  350. public function EndOfSeek() {
  351. $this->ResetError();
  352. if ($this->IsConnected()) {
  353. if ($this->active_row >= ($this->RowCount())) {
  354. return true;
  355. } else {
  356. return false;
  357. }
  358. } else {
  359. $this->SetError("No connection");
  360. return false;
  361. }
  362. }
  363. /**
  364. * Returns the last MySQL error as text
  365. *
  366. * @return string Error text from last known error
  367. */
  368. public function Error() {
  369. $error = $this->error_desc;
  370. if (empty($error)) {
  371. if ($this->error_number <> 0) {
  372. $error = "Unknown Error (#" . $this->error_number . ")";
  373. } else {
  374. $error = false;
  375. }
  376. } else {
  377. if ($this->error_number > 0) {
  378. $error .= " (#" . $this->error_number . ")";
  379. }
  380. }
  381. return $error;
  382. }
  383. /**
  384. * Returns the last MySQL error as a number
  385. *
  386. * @return integer Error number from last known error
  387. */
  388. public function ErrorNumber() {
  389. if (strlen($this->error_desc) > 0)
  390. {
  391. if ($this->error_number <> 0)
  392. {
  393. return $this->error_number;
  394. } else {
  395. return -1;
  396. }
  397. } else {
  398. return $this->error_number;
  399. }
  400. }
  401. /**
  402. * [STATIC] Converts any value of any datatype into boolean (true or false)
  403. *
  404. * @param mixed $value Value to analyze for TRUE or FALSE
  405. * @return boolean Returns TRUE or FALSE
  406. */
  407. static public function GetBooleanValue($value) {
  408. if (gettype($value) == "boolean") {
  409. if ($value == true) {
  410. return true;
  411. } else {
  412. return false;
  413. }
  414. } elseif (is_numeric($value)) {
  415. if ($value > 0) {
  416. return true;
  417. } else {
  418. return false;
  419. }
  420. } else {
  421. $cleaned = strtoupper(trim($value));
  422. if ($cleaned == "ON") {
  423. return true;
  424. } elseif ($cleaned == "SELECTED" || $cleaned == "CHECKED") {
  425. return true;
  426. } elseif ($cleaned == "YES" || $cleaned == "Y") {
  427. return true;
  428. } elseif ($cleaned == "TRUE" || $cleaned == "T") {
  429. return true;
  430. } else {
  431. return false;
  432. }
  433. }
  434. }
  435. /**
  436. * Returns the comments for fields in a table into an
  437. * array or NULL if the table has not got any fields
  438. *
  439. * @param string $table Table name
  440. * @return array An array that contains the column comments
  441. */
  442. public function GetColumnComments($table) {
  443. $this->ResetError();
  444. $records = mysql_query("SHOW FULL COLUMNS FROM " . $table);
  445. if (! $records) {
  446. $this->SetError();
  447. return false;
  448. } else {
  449. // Get the column names
  450. $columnNames = $this->GetColumnNames($table);
  451. if ($this->Error()) {
  452. return false;
  453. } else {
  454. $index = 0;
  455. // Fetchs the array to be returned (column 8 is field comment):
  456. while ($array_data = mysql_fetch_array($records)) {
  457. $columns[$index] = $array_data[8];
  458. $columns[$columnNames[$index++]] = $array_data[8];
  459. }
  460. return $columns;
  461. }
  462. }
  463. }
  464. /**
  465. * This function returns the number of columns or returns FALSE on error
  466. *
  467. * @param string $table (Optional) If a table name is not specified, the
  468. * column count is returned from the last query
  469. * @return integer The total count of columns
  470. */
  471. public function GetColumnCount($table = "") {
  472. $this->ResetError();
  473. if (empty($table)) {
  474. $result = mysql_num_fields($this->last_result);
  475. if (! $result) $this->SetError();
  476. } else {
  477. $records = mysql_query("SELECT * FROM " . $table . " LIMIT 1");
  478. if (! $records) {
  479. $this->SetError();
  480. $result = false;
  481. } else {
  482. $result = mysql_num_fields($records);
  483. $success = @mysql_free_result($records);
  484. if (! $success) {
  485. $this->SetError();
  486. $result = false;
  487. }
  488. }
  489. }
  490. return $result;
  491. }
  492. /**
  493. * This function returns the data type for a specified column. If
  494. * the column does not exists or no records exist, it returns FALSE
  495. *
  496. * @param string $column Column name or number (first column is 0)
  497. * @param string $table (Optional) If a table name is not specified, the
  498. * last returned records are used
  499. * @return string MySQL data (field) type
  500. */
  501. public function GetColumnDataType($column, $table = "") {
  502. $this->ResetError();
  503. if (empty($table)) {
  504. if ($this->RowCount() > 0) {
  505. if (is_numeric($column)) {
  506. return mysql_field_type($this->last_result, $column);
  507. } else {
  508. return mysql_field_type($this->last_result, $this->GetColumnID($column));
  509. }
  510. } else {
  511. return false;
  512. }
  513. } else {
  514. if (is_numeric($column)) $column = $this->GetColumnName($column, $table);
  515. $result = mysql_query("SELECT " . $column . " FROM " . $table . " LIMIT 1");
  516. if (mysql_num_fields($result) > 0) {
  517. return mysql_field_type($result, 0);
  518. } else {
  519. $this->SetError("The specified column or table does not exist, or no data was returned", -1);
  520. return false;
  521. }
  522. }
  523. }
  524. /**
  525. * This function returns the position of a column
  526. *
  527. * @param string $column Column name
  528. * @param string $table (Optional) If a table name is not specified, the
  529. * last returned records are used.
  530. * @return integer Column ID
  531. */
  532. public function GetColumnID($column, $table = "") {
  533. $this->ResetError();
  534. $columnNames = $this->GetColumnNames($table);
  535. if (! $columnNames) {
  536. return false;
  537. } else {
  538. $index = 0;
  539. $found = false;
  540. foreach ($columnNames as $columnName) {
  541. if ($columnName == $column) {
  542. $found = true;
  543. break;
  544. }
  545. $index++;
  546. }
  547. if ($found) {
  548. return $index;
  549. } else {
  550. $this->SetError("Column name not found", -1);
  551. return false;
  552. }
  553. }
  554. }
  555. /**
  556. * This function returns the field length or returns FALSE on error
  557. *
  558. * @param string $column Column name
  559. * @param string $table (Optional) If a table name is not specified, the
  560. * last returned records are used.
  561. * @return integer Field length
  562. */
  563. public function GetColumnLength($column, $table = "") {
  564. $this->ResetError();
  565. if (empty($table)) {
  566. if (is_numeric($column)) {
  567. $columnID = $column;
  568. } else {
  569. $columnID = $this->GetColumnID($column);
  570. }
  571. if (! $columnID) {
  572. return false;
  573. } else {
  574. $result = mysql_field_len($this->last_result, $columnID);
  575. if (! $result) {
  576. $this->SetError();
  577. return false;
  578. } else {
  579. return $result;
  580. }
  581. }
  582. } else {
  583. $records = mysql_query("SELECT " . $column . " FROM " . $table . " LIMIT 1");
  584. if (! $records) {
  585. $this->SetError();
  586. return false;
  587. }
  588. $result = mysql_field_len($records, 0);
  589. if (! $result) {
  590. $this->SetError();
  591. return false;
  592. } else {
  593. return $result;
  594. }
  595. }
  596. }
  597. /**
  598. * This function returns the name for a specified column number. If
  599. * the index does not exists or no records exist, it returns FALSE
  600. *
  601. * @param string $columnID Column position (0 is the first column)
  602. * @param string $table (Optional) If a table name is not specified, the
  603. * last returned records are used.
  604. * @return integer Field Length
  605. */
  606. public function GetColumnName($columnID, $table = "") {
  607. $this->ResetError();
  608. if (empty($table)) {
  609. if ($this->RowCount() > 0) {
  610. $result = mysql_field_name($this->last_result, $columnID);
  611. if (! $result) $this->SetError();
  612. } else {
  613. $result = false;
  614. }
  615. } else {
  616. $records = mysql_query("SELECT * FROM " . $table . " LIMIT 1");
  617. if (! $records) {
  618. $this->SetError();
  619. $result = false;
  620. } else {
  621. if (mysql_num_fields($records) > 0) {
  622. $result = mysql_field_name($records, $columnID);
  623. if (! $result) $this->SetError();
  624. } else {
  625. $result = false;
  626. }
  627. }
  628. }
  629. return $result;
  630. }
  631. /**
  632. * Returns the field names in a table or query in an array
  633. *
  634. * @param string $table (Optional) If a table name is not specified, the
  635. * last returned records are used
  636. * @return array An array that contains the column names
  637. */
  638. public function GetColumnNames($table = "") {
  639. $this->ResetError();
  640. if (empty($table)) {
  641. $columnCount = mysql_num_fields($this->last_result);
  642. if (! $columnCount) {
  643. $this->SetError();
  644. $columns = false;
  645. } else {
  646. for ($column = 0; $column < $columnCount; $column++) {
  647. $columns[] = mysql_field_name($this->last_result, $column);
  648. }
  649. }
  650. } else {
  651. $result = mysql_query("SHOW COLUMNS FROM " . $table);
  652. if (! $result) {
  653. $this->SetError();
  654. $columns = false;
  655. } else {
  656. while ($array_data = mysql_fetch_array($result)) {
  657. $columns[] = $array_data[0];
  658. }
  659. }
  660. }
  661. // Returns the array
  662. return $columns;
  663. }
  664. /**
  665. * This function returns the last query as an HTML table
  666. *
  667. * @param boolean $showCount (Optional) TRUE if you want to show the row count,
  668. * FALSE if you do not want to show the count
  669. * @param string $styleTable (Optional) Style information for the table
  670. * @param string $styleHeader (Optional) Style information for the header row
  671. * @param string $styleData (Optional) Style information for the cells
  672. * @return string HTML containing a table with all records listed
  673. */
  674. public function GetHTML($showCount = true, $styleTable = null, $styleHeader = null, $styleData = null) {
  675. if ($styleTable === null) {
  676. $tb = "border-collapse:collapse;empty-cells:show";
  677. } else {
  678. $tb = $styleTable;
  679. }
  680. if ($styleHeader === null) {
  681. $th = "border-width:1px;border-style:solid;background-color:navy;color:white";
  682. } else {
  683. $th = $styleHeader;
  684. }
  685. if ($styleData === null) {
  686. $td = "border-width:1px;border-style:solid";
  687. } else {
  688. $td = $styleData;
  689. }
  690. if ($this->last_result) {
  691. if ($this->RowCount() > 0) {
  692. $html = "";
  693. if ($showCount) $html = "Record Count: " . $this->RowCount() . "<br />\n";
  694. $html .= "<table style=\"$tb\" cellpadding=\"2\" cellspacing=\"2\">\n";
  695. $this->MoveFirst();
  696. $header = false;
  697. while ($member = mysql_fetch_object($this->last_result)) {
  698. if (!$header) {
  699. $html .= "\t<tr>\n";
  700. foreach ($member as $key => $value) {
  701. $html .= "\t\t<td style=\"$th\"><strong>" . htmlspecialchars($key) . "</strong></td>\n";
  702. }
  703. $html .= "\t</tr>\n";
  704. $header = true;
  705. }
  706. $html .= "\t<tr>\n";
  707. foreach ($member as $key => $value) {
  708. $html .= "\t\t<td style=\"$td\">" . htmlspecialchars($value) . "</td>\n";
  709. }
  710. $html .= "\t</tr>\n";
  711. }
  712. $this->MoveFirst();
  713. $html .= "</table>";
  714. } else {
  715. $html = "No records were returned.";
  716. }
  717. } else {
  718. $this->active_row = -1;
  719. $html = false;
  720. }
  721. return $html;
  722. }
  723. /**
  724. * Returns the last query as a JSON document
  725. *
  726. * @return string JSON containing all records listed
  727. */
  728. public function GetJSON() {
  729. if ($this->last_result) {
  730. if ($this->RowCount() > 0) {
  731. for ($i = 0, $il = mysql_num_fields($this->last_result); $i < $il; $i++) {
  732. $types[$i] = mysql_field_type($this->last_result, $i);
  733. }
  734. $json = '[';
  735. $this->MoveFirst();
  736. while ($member = mysql_fetch_object($this->last_result)) {
  737. $json .= json_encode($member) . ",";
  738. }
  739. $json .= ']';
  740. $json = str_replace("},]", "}]", $json);
  741. } else {
  742. $json = 'null';
  743. }
  744. } else {
  745. $this->active_row = -1;
  746. $json = 'null';
  747. }
  748. return $json;
  749. }
  750. /**
  751. * Returns the last autonumber ID field from a previous INSERT query
  752. *
  753. * @return integer ID number from previous INSERT query
  754. */
  755. public function GetLastInsertID() {
  756. return $this->last_insert_id;
  757. }
  758. /**
  759. * Returns the last SQL statement executed
  760. *
  761. * @return string Current SQL query string
  762. */
  763. public function GetLastSQL() {
  764. return $this->last_sql;
  765. }
  766. /**
  767. * This function returns table names from the database
  768. * into an array. If the database does not contains
  769. * any tables, the returned value is FALSE
  770. *
  771. * @return array An array that contains the table names
  772. */
  773. public function GetTables() {
  774. $this->ResetError();
  775. // Query to get the tables in the current database:
  776. $records = mysql_query("SHOW TABLES");
  777. if (! $records) {
  778. $this->SetError();
  779. return FALSE;
  780. } else {
  781. while ($array_data = mysql_fetch_array($records)) {
  782. $tables[] = $array_data[0];
  783. }
  784. // Returns the array or NULL
  785. if (count($tables) > 0) {
  786. return $tables;
  787. } else {
  788. return FALSE;
  789. }
  790. }
  791. }
  792. /**
  793. * Returns the last query as an XML Document
  794. *
  795. * @return string XML containing all records listed
  796. */
  797. public function GetXML() {
  798. // Create a new XML document
  799. $doc = new DomDocument('1.0'); // ,'UTF-8');
  800. // Create the root node
  801. $root = $doc->createElement('root');
  802. $root = $doc->appendChild($root);
  803. // If there was a result set
  804. if (is_resource($this->last_result)) {
  805. // Show the row count and query
  806. $root->setAttribute('rows',
  807. ($this->RowCount() ? $this->RowCount() : 0));
  808. $root->setAttribute('query', $this->last_sql);
  809. $root->setAttribute('error', "");
  810. // process one row at a time
  811. $rowCount = 0;
  812. while ($row = mysql_fetch_assoc($this->last_result)) {
  813. // Keep the row count
  814. $rowCount = $rowCount + 1;
  815. // Add node for each row
  816. $element = $doc->createElement('row');
  817. $element = $root->appendChild($element);
  818. $element->setAttribute('index', $rowCount);
  819. // Add a child node for each field
  820. foreach ($row as $fieldname => $fieldvalue) {
  821. $child = $doc->createElement($fieldname);
  822. $child = $element->appendChild($child);
  823. // $fieldvalue = iconv("ISO-8859-1", "UTF-8", $fieldvalue);
  824. $fieldvalue = htmlspecialchars($fieldvalue);
  825. $value = $doc->createTextNode($fieldvalue);
  826. $value = $child->appendChild($value);
  827. } // foreach
  828. } // while
  829. } else {
  830. // Process any errors
  831. $root->setAttribute('rows', 0);
  832. $root->setAttribute('query', $this->last_sql);
  833. if ($this->Error()) {
  834. $root->setAttribute('error', $this->Error());
  835. } else {
  836. $root->setAttribute('error', "No query has been executed.");
  837. }
  838. }
  839. // Show the XML document
  840. return $doc->saveXML();
  841. }
  842. /**
  843. * Determines if a query contains any rows
  844. *
  845. * @param string $sql [Optional] If specified, the query is first executed
  846. * Otherwise, the last query is used for comparison
  847. * @return boolean TRUE if records exist, FALSE if not or query error
  848. */
  849. public function HasRecords($sql = "") {
  850. if (strlen($sql) > 0) {
  851. $this->Query($sql);
  852. if ($this->Error()) return false;
  853. }
  854. if ($this->RowCount() > 0) {
  855. return true;
  856. } else {
  857. return false;
  858. }
  859. }
  860. /**
  861. * Inserts a row into a table in the connected database
  862. *
  863. * @param string $tableName The name of the table
  864. * @param array $valuesArray An associative array containing the column
  865. * names as keys and values as data. The values
  866. * must be SQL ready (i.e. quotes around
  867. * strings, formatted dates, ect)
  868. * @return integer Returns last insert ID on success or FALSE on failure
  869. */
  870. public function InsertRow($tableName, $valuesArray) {
  871. $this->ResetError();
  872. if (! $this->IsConnected()) {
  873. $this->SetError("No connection");
  874. return false;
  875. } else {
  876. // Execute the query
  877. $sql = self::BuildSQLInsert($tableName, $valuesArray);
  878. if (! $this->Query($sql)) {
  879. return false;
  880. } else {
  881. return $this->GetLastInsertID();
  882. }
  883. }
  884. }
  885. /**
  886. * Determines if a valid connection to the database exists
  887. *
  888. * @return boolean TRUE idf connectect or FALSE if not connected
  889. */
  890. public function IsConnected() {
  891. if (gettype($this->mysql_link) == "resource") {
  892. return true;
  893. } else {
  894. return false;
  895. }
  896. }
  897. /**
  898. * [STATIC] Determines if a value of any data type is a date PHP can convert
  899. *
  900. * @param date/string $value
  901. * @return boolean Returns TRUE if value is date or FALSE if not date
  902. */
  903. static public function IsDate($value) {
  904. $date = date('Y', strtotime($value));
  905. if ($date == "1969" || $date == '') {
  906. return false;
  907. } else {
  908. return true;
  909. }
  910. }
  911. /**
  912. * Stop executing (die/exit) and show last MySQL error message
  913. *
  914. */
  915. public function Kill($message = "") {
  916. if (strlen($message) > 0) {
  917. exit($message);
  918. } else {
  919. exit($this->Error());
  920. }
  921. }
  922. /**
  923. * Seeks to the beginning of the records
  924. *
  925. * @return boolean Returns TRUE on success or FALSE on error
  926. */
  927. public function MoveFirst() {
  928. $this->ResetError();
  929. if (! $this->Seek(0)) {
  930. $this->SetError();
  931. return false;
  932. } else {
  933. $this->active_row = 0;
  934. return true;
  935. }
  936. }
  937. /**
  938. * Seeks to the end of the records
  939. *
  940. * @return boolean Returns TRUE on success or FALSE on error
  941. */
  942. public function MoveLast() {
  943. $this->ResetError();
  944. $this->active_row = $this->RowCount() - 1;
  945. if (! $this->Error()) {
  946. if (! $this->Seek($this->active_row)) {
  947. return false;
  948. } else {
  949. return true;
  950. }
  951. } else {
  952. return false;
  953. }
  954. }
  955. /**
  956. * Connect to specified MySQL server
  957. *
  958. * @param string $database (Optional) Database name
  959. * @param string $server (Optional) Host address
  960. * @param string $username (Optional) User name
  961. * @param string $password (Optional) Password
  962. * @param string $charset (Optional) Character set
  963. * @param boolean $pcon (Optional) Persistant connection
  964. * @return boolean Returns TRUE on success or FALSE on error
  965. */
  966. public function Open($database = null, $server = null, $username = null,
  967. $password = null, $charset = null, $pcon = false) {
  968. $this->ResetError();
  969. // Use defaults?
  970. if ($database !== null) $this->db_dbname = $database;
  971. if ($server !== null) $this->db_host = $server;
  972. if ($username !== null) $this->db_user = $username;
  973. if ($password !== null) $this->db_pass = $password;
  974. if ($charset !== null) $this->db_charset = $charset;
  975. if (is_bool($pcon)) $this->db_pcon = $pcon;
  976. $this->active_row = -1;
  977. // Open persistent or normal connection
  978. if ($pcon) {
  979. $this->mysql_link = @mysql_pconnect(
  980. $this->db_host, $this->db_user, $this->db_pass);
  981. } else {
  982. $this->mysql_link = @mysql_connect (
  983. $this->db_host, $this->db_user, $this->db_pass);
  984. }
  985. // Connect to mysql server failed?
  986. if (! $this->IsConnected()) {
  987. $this->SetError();
  988. return false;
  989. } else {
  990. // Select a database (if specified)
  991. if (strlen($this->db_dbname) > 0) {
  992. if (strlen($this->db_charset) == 0) {
  993. if (! $this->SelectDatabase($this->db_dbname)) {
  994. return false;
  995. } else {
  996. return true;
  997. }
  998. } else {
  999. if (! $this->SelectDatabase(
  1000. $this->db_dbname, $this->db_charset)) {
  1001. return false;
  1002. } else {
  1003. return true;
  1004. }
  1005. }
  1006. } else {
  1007. return true;
  1008. }
  1009. }
  1010. }
  1011. /**
  1012. * Executes the given SQL query and returns the records
  1013. *
  1014. * @param string $sql The query string should not end with a semicolon
  1015. * @return object PHP 'mysql result' resource object containing the records
  1016. * on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns;
  1017. * TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP
  1018. * AND FALSE on all errors (setting the local Error message)
  1019. */
  1020. public function Query($sql) {
  1021. $this->ResetError();
  1022. $this->last_sql = $sql;
  1023. $this->last_result = @mysql_query($sql, $this->mysql_link);
  1024. if(! $this->last_result) {
  1025. $this->active_row = -1;
  1026. $this->SetError();
  1027. return false;
  1028. } else {
  1029. if (strpos(strtolower($sql), "insert") === 0) {
  1030. $this->last_insert_id = mysql_insert_id();
  1031. if ($this->last_insert_id === false) {
  1032. $this->SetError();
  1033. return false;
  1034. } else {
  1035. $numrows = 0;
  1036. $this->active_row = -1;
  1037. return $this->last_result;
  1038. }
  1039. } else if(strpos(strtolower($sql), "select") === 0) {
  1040. $numrows = mysql_num_rows($this->last_result);
  1041. if ($numrows > 0) {
  1042. $this->active_row = 0;
  1043. } else {
  1044. $this->active_row = -1;
  1045. }
  1046. $this->last_insert_id = 0;
  1047. return $this->last_result;
  1048. } else {
  1049. return $this->last_result;
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Executes the given SQL query and returns a multi-dimensional array
  1055. *
  1056. * @param string $sql The query string should not end with a semicolon
  1057. * @param integer $resultType (Optional) The type of array
  1058. * Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1059. * @return array A multi-dimensional array containing all the data
  1060. * returned from the query or FALSE on all errors
  1061. */
  1062. public function QueryArray($sql, $resultType = MYSQL_BOTH) {
  1063. $this->Query($sql);
  1064. if (! $this->Error()) {
  1065. return $this->RecordsArray($resultType);
  1066. } else {
  1067. return false;
  1068. }
  1069. }
  1070. /**
  1071. * Executes the given SQL query and returns only one (the first) row
  1072. *
  1073. * @param string $sql The query string should not end with a semicolon
  1074. * @return object PHP resource object containing the first row or
  1075. * FALSE if no row is returned from the query
  1076. */
  1077. public function QuerySingleRow($sql) {
  1078. $this->Query($sql);
  1079. if ($this->RowCount() > 0) {
  1080. return $this->Row();
  1081. } else {
  1082. return false;
  1083. }
  1084. }
  1085. /**
  1086. * Executes the given SQL query and returns the first row as an array
  1087. *
  1088. * @param string $sql The query string should not end with a semicolon
  1089. * @param integer $resultType (Optional) The type of array
  1090. * Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1091. * @return array An array containing the first row or FALSE if no row
  1092. * is returned from the query
  1093. */
  1094. public function QuerySingleRowArray($sql, $resultType = MYSQL_BOTH) {
  1095. $this->Query($sql);
  1096. if ($this->RowCount() > 0) {
  1097. return $this->RowArray(null, $resultType);
  1098. } else {
  1099. return false;
  1100. }
  1101. }
  1102. /**
  1103. * Executes a query and returns a single value. If more than one row
  1104. * is returned, only the first value in the first column is returned.
  1105. *
  1106. * @param string $sql The query string should not end with a semicolon
  1107. * @return mixed The value returned or FALSE if no value
  1108. */
  1109. public function QuerySingleValue($sql) {
  1110. $this->Query($sql);
  1111. if ($this->RowCount() > 0 && $this->GetColumnCount() > 0) {
  1112. $row = $this->RowArray(null, MYSQL_NUM);
  1113. return $row[0];
  1114. } else {
  1115. return false;
  1116. }
  1117. }
  1118. /**
  1119. * Executes the given SQL query, measures it, and saves the total duration
  1120. * in microseconds
  1121. *
  1122. * @param string $sql The query string should not end with a semicolon
  1123. * @return object PHP 'mysql result' resource object containing the records
  1124. * on SELECT, SHOW, DESCRIBE or EXPLAIN queries and returns
  1125. * TRUE or FALSE for all others i.e. UPDATE, DELETE, DROP
  1126. */
  1127. public function QueryTimed($sql) {
  1128. $this->TimerStart();
  1129. $result = $this->Query($sql);
  1130. $this->TimerStop();
  1131. return $result;
  1132. }
  1133. /**
  1134. * Returns the records from the last query
  1135. *
  1136. * @return object PHP 'mysql result' resource object containing the records
  1137. * for the last query executed
  1138. */
  1139. public function Records() {
  1140. return $this->last_result;
  1141. }
  1142. /**
  1143. * Returns all records from last query and returns contents as array
  1144. * or FALSE on error
  1145. *
  1146. * @param integer $resultType (Optional) The type of array
  1147. * Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1148. * @return Records in array form
  1149. */
  1150. public function RecordsArray($resultType = MYSQL_BOTH) {
  1151. $this->ResetError();
  1152. if ($this->last_result) {
  1153. if (! mysql_data_seek($this->last_result, 0)) {
  1154. $this->SetError();
  1155. return false;
  1156. } else {
  1157. //while($member = mysql_fetch_object($this->last_result)){
  1158. while ($member = mysql_fetch_array($this->last_result, $resultType)){
  1159. $members[] = $member;
  1160. }
  1161. mysql_data_seek($this->last_result, 0);
  1162. $this->active_row = 0;
  1163. return $members;
  1164. }
  1165. } else {
  1166. $this->active_row = -1;
  1167. $this->SetError("No query results exist", -1);
  1168. return false;
  1169. }
  1170. }
  1171. /**
  1172. * Frees memory used by the query results and returns the function result
  1173. *
  1174. * @return boolean Returns TRUE on success or FALSE on failure
  1175. */
  1176. public function Release() {
  1177. $this->ResetError();
  1178. if (! $this->last_result) {
  1179. $success = true;
  1180. } else {
  1181. $success = @mysql_free_result($this->last_result);
  1182. if (! $success) $this->SetError();
  1183. }
  1184. return $success;
  1185. }
  1186. /**
  1187. * Clears the internal variables from any error information
  1188. *
  1189. */
  1190. private function ResetError() {
  1191. $this->error_desc = '';
  1192. $this->error_number = 0;
  1193. }
  1194. /**
  1195. * Reads the current row and returns contents as a
  1196. * PHP object or returns false on error
  1197. *
  1198. * @param integer $optional_row_number (Optional) Use to specify a row
  1199. * @return object PHP object or FALSE on error
  1200. */
  1201. public function Row($optional_row_number = null) {
  1202. $this->ResetError();
  1203. if (! $this->last_result) {
  1204. $this->SetError("No query results exist", -1);
  1205. return false;
  1206. } elseif ($optional_row_number === null) {
  1207. if (($this->active_row) > $this->RowCount()) {
  1208. $this->SetError("Cannot read past the end of the records", -1);
  1209. return false;
  1210. } else {
  1211. $this->active_row++;
  1212. }
  1213. } else {
  1214. if ($optional_row_number >= $this->RowCount()) {
  1215. $this->SetError("Row number is greater than the total number of rows", -1);
  1216. return false;
  1217. } else {
  1218. $this->active_row = $optional_row_number;
  1219. $this->Seek($optional_row_number);
  1220. }
  1221. }
  1222. $row = mysql_fetch_object($this->last_result);
  1223. if (! $row) {
  1224. $this->SetError();
  1225. return false;
  1226. } else {
  1227. return $row;
  1228. }
  1229. }
  1230. /**
  1231. * Reads the current row and returns contents as an
  1232. * array or returns false on error
  1233. *
  1234. * @param integer $optional_row_number (Optional) Use to specify a row
  1235. * @param integer $resultType (Optional) The type of array
  1236. * Values can be: MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
  1237. * @return array Array that corresponds to fetched row or FALSE if no rows
  1238. */
  1239. public function RowArray($optional_row_number = null, $resultType = MYSQL_BOTH) {
  1240. $this->ResetError();
  1241. if (! $this->last_result) {
  1242. $this->SetError("No query results exist", -1);
  1243. return false;
  1244. } elseif ($optional_row_number === null) {
  1245. if (($this->active_row) > $this->RowCount()) {
  1246. $this->SetError("Cannot read past the end of the records", -1);
  1247. return false;
  1248. } else {
  1249. $this->active_row++;
  1250. }
  1251. } else {
  1252. if ($optional_row_number >= $this->RowCount()) {
  1253. $this->SetError("Row number is greater than the total number of rows", -1);
  1254. return false;
  1255. } else {
  1256. $this->active_row = $optional_row_number;
  1257. $this->Seek($optional_row_number);
  1258. }
  1259. }
  1260. $row = mysql_fetch_array($this->last_result, $resultType);
  1261. if (! $row) {
  1262. $this->SetError();
  1263. return false;
  1264. } else {
  1265. return $row;
  1266. }
  1267. }
  1268. /**
  1269. * Returns the last query row count
  1270. *
  1271. * @return integer Row count or FALSE on error
  1272. */
  1273. public function RowCount() {
  1274. $this->ResetError();
  1275. if (! $this->IsConnected()) {
  1276. $this->SetError("No connection", -1);
  1277. return false;
  1278. } elseif (! $this->last_result) {
  1279. $this->SetError("No query results exist", -1);
  1280. return false;
  1281. } else {
  1282. $result = @mysql_num_rows($this->last_result);
  1283. if (! $result) {
  1284. $this->SetError();
  1285. return false;
  1286. } else {
  1287. return $result;
  1288. }
  1289. }
  1290. }
  1291. /**
  1292. * Sets the internal database pointer to the
  1293. * specified row number and returns the result
  1294. *
  1295. * @param integer $row_number Row number
  1296. * @return object Fetched row as PHP object
  1297. */
  1298. public function Seek($row_number) {
  1299. $this->ResetError();
  1300. $row_count = $this->RowCount();
  1301. if (! $row_count) {
  1302. return false;
  1303. } elseif ($row_number >= $row_count) {
  1304. $this->SetError("Seek parameter is greater than the total number of rows", -1);
  1305. return false;
  1306. } else {
  1307. $this->active_row = $row_number;
  1308. $result = mysql_data_seek($this->last_result, $row_number);
  1309. if (! $result) {
  1310. $this->SetError();
  1311. return false;
  1312. } else {
  1313. $record = mysql_fetch_row($this->last_result);
  1314. if (! $record) {
  1315. $this->SetError();
  1316. return false;
  1317. } else {
  1318. // Go back to the record after grabbing it
  1319. mysql_data_seek($this->last_result, $row_number);
  1320. return $record;
  1321. }
  1322. }
  1323. }
  1324. }
  1325. /**
  1326. * Returns the current cursor row location
  1327. *
  1328. * @return integer Current row number
  1329. */
  1330. public function SeekPosition() {
  1331. return $this->active_row;
  1332. }
  1333. /**
  1334. * Selects a different database and character set
  1335. *
  1336. * @param string $database Database name
  1337. * @param string $charset (Optional) Character set (i.e. utf8)
  1338. * @return boolean Returns TRUE on success or FALSE on error
  1339. */
  1340. public function SelectDatabase($database, $charset = "") {
  1341. $return_value = true;
  1342. if (! $charset) $charset = $this->db_charset;
  1343. $this->ResetError();
  1344. if (! (mysql_select_db($database))) {
  1345. $this->SetError();
  1346. $return_value = false;
  1347. } else {
  1348. if ((strlen($charset) > 0)) {
  1349. if (! (mysql_query("SET CHARACTER SET '{$charset}'", $this->mysql_link))) {
  1350. $this->SetError();
  1351. $return_value = false;
  1352. }
  1353. }
  1354. }
  1355. return $return_value;
  1356. }
  1357. /**
  1358. * Gets rows in a table based on a WHERE filter
  1359. *
  1360. * @param string $tableName The name of the table
  1361. * @param array $whereArray (Optional) An associative array containing the
  1362. * column names as keys and values as data. The
  1363. * values must be SQL ready (i.e. quotes around
  1364. * strings, formatted dates, ect)
  1365. * @param array/string $columns (Optional) The column or list of columns to select
  1366. * @param array/string $sortColumns (Optional) Column or list of columns to sort by
  1367. * @param boolean $sortAscending (Optional) TRUE for ascending; FALSE for descending
  1368. * This only works if $sortColumns are specified
  1369. * @param integer/string $limit (Optional) The limit of rows to return
  1370. * @return boolean Returns records on success or FALSE on error
  1371. */
  1372. public function SelectRows($tableName, $whereArray = null, $columns = null,
  1373. $sortColumns = null, $sortAscending = true,
  1374. $limit = null) {
  1375. $this->ResetError();
  1376. if (! $this->IsConnected()) {
  1377. $this->SetError("No connection");
  1378. return false;
  1379. } else {
  1380. $sql = self::BuildSQLSelect($tableName, $whereArray,
  1381. $columns, $sortColumns, $sortAscending, $limit);
  1382. // Execute the UPDATE
  1383. if (! $this->Query($sql)) {
  1384. return $this->last_result;
  1385. } else {
  1386. return true;
  1387. }
  1388. }
  1389. }
  1390. /**
  1391. * Retrieves all rows in a specified table
  1392. *
  1393. * @param string $tableName The name of the table
  1394. * @return boolean Returns records on success or FALSE on error
  1395. */
  1396. public function SelectTable($tableName) {
  1397. return $this->SelectRows($tableName);
  1398. }
  1399. /**
  1400. * Sets the local variables with the last error information
  1401. *
  1402. * @param string $errorMessage The error description
  1403. * @param integer $errorNumber The error number
  1404. */
  1405. private function SetError($errorMessage = "", $errorNumber = 0) {
  1406. try {
  1407. if (strlen($errorMessage) > 0) {
  1408. $this->error_desc = $errorMessage;
  1409. } else {
  1410. if ($this->IsConnected()) {
  1411. $this->error_desc = mysql_error($this->mysql_link);
  1412. } else {
  1413. $this->error_desc = mysql_error();
  1414. }
  1415. }
  1416. if ($errorNumber <> 0) {
  1417. $this->error_number = $errorNumber;
  1418. } else {
  1419. if ($this->IsConnected()) {
  1420. $this->error_number = @mysql_errno($this->mysql_link);
  1421. } else {
  1422. $this->error_number = @mysql_errno();
  1423. }
  1424. }
  1425. } catch(Exception $e) {
  1426. $this->error_desc = $e->getMessage();
  1427. $this->error_number = -999;
  1428. }
  1429. if ($this->ThrowExceptions) {
  1430. if (isset($this->error_desc) && $this->error_desc != NULL) {
  1431. throw new Exception($this->error_desc . ' (' . __LINE__ . ')');
  1432. }
  1433. }
  1434. }
  1435. /**
  1436. * [STATIC] Converts a boolean into a formatted TRUE or FALSE value of choice
  1437. *
  1438. * @param mixed $value value to analyze for TRUE or FALSE
  1439. * @param mixed $trueValue value to use if TRUE
  1440. * @param mixed $falseValue value to use if FALSE
  1441. * @param string $datatype Use SQLVALUE constants or the strings:
  1442. * string, text, varchar, char, boolean, bool,
  1443. * Y-N, T-F, bit, date, datetime, time, integer,
  1444. * int, number, double, float
  1445. * @return string SQL formatted value of the specified data type
  1446. */
  1447. static public function SQLBooleanValue($value, $trueValue, $falseValue, $datatype = self::SQLVALUE_TEXT) {
  1448. if (self::GetBooleanValue($value)) {
  1449. $return_value = self::SQLValue($trueValue, $datatype);
  1450. } else {
  1451. $return_value = self::SQLValue($falseValue, $datatype);
  1452. }
  1453. return $return_value;
  1454. }
  1455. /**
  1456. * [STATIC] Returns string suitable for SQL
  1457. *
  1458. * @param string $value
  1459. * @return string SQL formatted value
  1460. */
  1461. static public function SQLFix($value) {
  1462. return @addslashes($value);
  1463. }
  1464. /**
  1465. * [STATIC] Returns MySQL string as normal string
  1466. *
  1467. * @param string $value
  1468. * @return string
  1469. */
  1470. static public function SQLUnfix($value) {
  1471. return @stripslashes($value);
  1472. }
  1473. /**
  1474. * [STATIC] Formats any value into a string suitable for SQL statements
  1475. * (NOTE: Also supports data types returned from the gettype function)
  1476. *
  1477. * @param mixed $value Any value of any type to be formatted to SQL
  1478. * @param string $datatype Use SQLVALUE constants or the strings:
  1479. * string, text, varchar, char, boolean, bool,
  1480. * Y-N, T-F, bit, date, datetime, time, integer,
  1481. * int, number, double, float
  1482. * @return string
  1483. */
  1484. static public function SQLValue($value, $datatype = self::SQLVALUE_TEXT) {
  1485. $return_value = "";
  1486. switch (strtolower(trim($datatype))) {
  1487. case "text":
  1488. case "string":
  1489. case "varchar":
  1490. case "char":
  1491. if (strlen($value) == 0) {
  1492. $return_value = "NULL";
  1493. } else {
  1494. if (get_magic_quotes_gpc()) {
  1495. $value = stripslashes($value);
  1496. }
  1497. $return_value = "'" . str_replace("'", "''", $value) . "'";
  1498. }
  1499. break;
  1500. case "number":
  1501. case "integer":
  1502. case "int":
  1503. case "double":
  1504. case "float":
  1505. if (is_numeric($value)) {
  1506. $return_value = $value;
  1507. } else {
  1508. $return_value = "NULL";
  1509. }
  1510. break;
  1511. case "boolean": //boolean to use this with a bit field
  1512. case "bool":
  1513. case "bit":
  1514. if (self::GetBooleanValue($value)) {
  1515. $return_value = "1";
  1516. } else {
  1517. $return_value = "0";
  1518. }
  1519. break;
  1520. case "y-n": //boolean to use this with a char(1) field
  1521. if (self::GetBooleanValue($value)) {
  1522. $return_value = "'Y'";
  1523. } else {
  1524. $return_value = "'N'";
  1525. }
  1526. break;
  1527. case "t-f": //boolean to use this with a char(1) field
  1528. if (self::GetBooleanValue($value)) {
  1529. $return_value = "'T'";
  1530. } else {
  1531. $return_value = "'F'";
  1532. }
  1533. break;
  1534. case "date":
  1535. if (self::IsDate($value)) {
  1536. $return_value = "'" . date('Y-m-d', strtotime($value)) . "'";
  1537. } else {
  1538. $return_value = "NULL";
  1539. }
  1540. break;
  1541. case "datetime":
  1542. if (self::IsDate($value)) {
  1543. $return_value = "'" . date('Y-m-d H:i:s', strtotime($value)) . "'";
  1544. } else {
  1545. $return_value = "NULL";
  1546. }
  1547. break;
  1548. case "time":
  1549. if (self::IsDate($value)) {
  1550. $return_value = "'" . date('H:i:s', strtotime($value)) . "'";
  1551. } else {
  1552. $return_value = "NULL";
  1553. }
  1554. break;
  1555. default:
  1556. exit("ERROR: Invalid data type specified in SQLValue method");
  1557. }
  1558. return $return_value;
  1559. }
  1560. /**
  1561. * Returns last measured duration (time between TimerStart and TimerStop)
  1562. *
  1563. * @param integer $decimals (Optional) The number of decimal places to show
  1564. * @return Float Microseconds elapsed
  1565. */
  1566. public function TimerDuration($decimals = 4) {
  1567. return number_format($this->time_diff, $decimals);
  1568. }
  1569. /**
  1570. * Starts time measurement (in microseconds)
  1571. *
  1572. */
  1573. public function TimerStart() {
  1574. $parts = explode(" ", microtime());
  1575. $this->time_diff = 0;
  1576. $this->time_start = $parts[1].substr($parts[0],1);
  1577. }
  1578. /**
  1579. * Stops time measurement (in microseconds)
  1580. *
  1581. */
  1582. public function TimerStop() {
  1583. $parts = explode(" ", microtime());
  1584. $time_stop = $parts[1].substr($parts[0],1);
  1585. $this->time_diff = ($time_stop - $this->time_start);
  1586. $this->time_start = 0;
  1587. }
  1588. /**
  1589. * Starts a transaction
  1590. *
  1591. * @return boolean Returns TRUE on success or FALSE on error
  1592. */
  1593. public function TransactionBegin() {
  1594. $this->ResetError();
  1595. if (! $this->IsConnected()) {
  1596. $this->SetError("No connection");
  1597. return false;
  1598. } else {

Large files files are truncated, but you can click here to view the full file