PageRenderTime 34ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/CMySQL.php

https://github.com/stargazers/CMySQL
PHP | 401 lines | 149 code | 58 blank | 194 comment | 20 complexity | a34843e00e74d0d00842abc5a38b579d MD5 | raw file
  1. <?php
  2. /*
  3. Class for using MySQL database with PHP.
  4. Copyright (C) 2008, 2009, 2011 Aleksi Räsänen <aleksi.rasanen@runosydan.net>
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU Affero General Public License as
  7. published by the Free Software Foundation, either version 3 of the
  8. License, or (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Affero General Public License for more details.
  13. You should have received a copy of the GNU Affero General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. // ***********************************************
  17. // CMySQL
  18. /*!
  19. @brief Class for MySQL databases
  20. @author Aleksi Räsänen
  21. @email aleksi.rasanen@runosydan.net
  22. @copyright Aleksi Räsänen, 2008-2011
  23. @license GNU AGPL
  24. */
  25. // ***********************************************
  26. class CMySQL
  27. {
  28. //! This will keep information if we are connected or not
  29. private $_isConnected = false;
  30. //! Last executed query
  31. private $_lastQuery = '';
  32. //! Results of last query
  33. private $_lastResult = '';
  34. //! Database connection
  35. private $_connection = '';
  36. //! Last executed INSERT INTO -query insertion ID
  37. private $lastInsertID = '';
  38. //***************************************************
  39. // __construct
  40. /*!
  41. @brief Class constructor. If we give a file as a
  42. parameter, then we read configuration from
  43. that file and connect database directly.
  44. @param $settingsFile Database settings. All settings
  45. must be in associative array $db where must
  46. exists keys server, username, password, port
  47. and database.
  48. @return Database connection
  49. */
  50. //***************************************************
  51. public function __construct( $settingsFile = '' )
  52. {
  53. // If config file is given and it exists, try to connect
  54. if( $settingsFile != '' && file_exists( $settingsFile ) )
  55. {
  56. include $settingsFile;
  57. $this->_connection = $this->connect( $db['server'] ,
  58. $db['username'], $db['password'], $db['port'],
  59. $db['database'] );
  60. // Return created connection
  61. return $this->_connection;
  62. }
  63. }
  64. // ***********************************************
  65. // query
  66. /*!
  67. @brief Execute query
  68. @param $query SQL query
  69. @return Last query results. On error we throw
  70. an Exception.
  71. */
  72. // ***********************************************
  73. public function query( $query )
  74. {
  75. // Execute query only if we have connected
  76. if( $this->_isConnected )
  77. {
  78. // Save last query to class variable
  79. $this->_lastQuery = $query;
  80. // Execute query
  81. $ret = @mysql_query( $query, $this->_connection );
  82. // If there were error, throw Exception
  83. if( mysql_error() != '' )
  84. throw new Exception( 'MySQL error: ' . mysql_error() );
  85. // Save query results to class variable
  86. $this->_lastResult = $ret;
  87. // Get last insert ID
  88. $this->lastInsertID = mysql_insert_id();
  89. // Return last query resultset
  90. return $ret;
  91. }
  92. else
  93. {
  94. throw new Exception( 'You are not connected to database!' );
  95. }
  96. }
  97. // ***********************************************
  98. // setConnection
  99. /*!
  100. @brief Set connection. This can be used if
  101. we want to use already existing
  102. database connection instead of creating
  103. new connection.
  104. @param $connection Database connection handle
  105. */
  106. // ***********************************************
  107. public function setConnection( $connection )
  108. {
  109. $this->_isConnected = true;
  110. $this->_connection = $connection;
  111. }
  112. // ***********************************************
  113. // getConnection
  114. /*!
  115. @brief Return handle of a connection
  116. @return Connection handle
  117. */
  118. // ***********************************************
  119. public function getConnection()
  120. {
  121. return $this->_connection;
  122. }
  123. // ***********************************************
  124. // disconnect
  125. /*!
  126. @brief Disconnects connection to database server
  127. */
  128. // ***********************************************
  129. public function disconnect()
  130. {
  131. // Try to disconnect only if conncetion is open
  132. if( $this->_isConnected )
  133. {
  134. $ret = @mysql_close();
  135. // If connection closed fine, update status
  136. if( $ret )
  137. $this->_isConnected = false;
  138. }
  139. else
  140. {
  141. throw new Exception( 'Can\'t disconnect because \
  142. you are not connected!' );
  143. }
  144. }
  145. // ***********************************************
  146. // getLastQuery
  147. /*!
  148. @brief Return last executed query
  149. @return Last executed query in string
  150. */
  151. // ***********************************************
  152. public function getLastQuery()
  153. {
  154. return $this->_lastQuery;
  155. }
  156. // ***********************************************
  157. // getLastResult
  158. /*!
  159. @brief Returns last resultset
  160. @return Results of last query in resultset
  161. */
  162. // ***********************************************
  163. public function getLastResult()
  164. {
  165. return $this->_lastResult;
  166. }
  167. // ***********************************************
  168. // fetchAssoc
  169. /*!
  170. @brief Create associative array from resultset
  171. @param $db_ret Resultset
  172. @return Associative array
  173. */
  174. // ***********************************************
  175. public function fetchAssoc( $db_ret )
  176. {
  177. // Get number of rows
  178. $numRows = @mysql_num_rows( $db_ret );
  179. // Here we store results
  180. $assocArray = array();
  181. // Create assoc array
  182. for( $i=0; $i < $numRows; $i++ )
  183. {
  184. // Split row to assoc array
  185. $row = mysql_fetch_assoc( $db_ret );
  186. // Add row to assoc array
  187. $assocArray[] = $row;
  188. }
  189. // Return assoc array
  190. return $assocArray;
  191. }
  192. // ***********************************************
  193. // connect
  194. /*!
  195. @brief Connect to database server
  196. @param $server Database server
  197. @param $username Database username
  198. @param $password Database password
  199. @param [$port] Database port number
  200. @param [$database] Database to select
  201. @return Connection. If failed, throws an Exception.
  202. */
  203. // ***********************************************
  204. public function connect( $server, $username, $password, $port = ''
  205. , $database = '' )
  206. {
  207. if( $port == '' )
  208. $ret = @mysql_connect( $server, $username, $password );
  209. else
  210. $ret = @mysql_connect( $server, $username, $password, $port );
  211. // If connection failed, throw new Exception
  212. if(! $ret )
  213. {
  214. throw new Exception( 'Failed to connect database server! Error: '
  215. . mysql_error() );
  216. }
  217. else
  218. {
  219. // Save status so we can know that we are connected
  220. $this->_isConnected = true;
  221. // Select database if param $database was given
  222. if( $database != '' )
  223. $this->selectDatabase( $database );
  224. // Save database connection
  225. $this->_connection = $ret;
  226. }
  227. // Return created cnnection
  228. return $ret;
  229. }
  230. // ***********************************************
  231. // selectDatabase
  232. /*!
  233. @brief Select database to use
  234. @param $database Database what we want to use
  235. */
  236. // ***********************************************
  237. public function selectDatabase( $database )
  238. {
  239. $ret = @mysql_select_db( $database );
  240. // If selection failed, throw new Exception
  241. if(! $ret )
  242. {
  243. throw new Exception( 'Failed to select database!' );
  244. }
  245. }
  246. // ***********************************************
  247. // isConnected
  248. /*!
  249. @brief Tells if we are connected or not
  250. @return True if connected, otherwise false
  251. */
  252. // ***********************************************
  253. public function isConnected()
  254. {
  255. return $this->_isConnected;
  256. }
  257. // ***********************************************
  258. // numRows
  259. /*!
  260. @brief Get number of rows in resultset
  261. @param [$db_ret] Query results where we want
  262. to read number of rows. If this is not
  263. given, then we use local variable
  264. where is stored last query results.
  265. If that is not found, then we throw
  266. an Exception.
  267. @return Number of rows
  268. */
  269. // ***********************************************
  270. public function numRows( $db_ret = '' )
  271. {
  272. if( $db_ret != '' )
  273. {
  274. return @mysql_num_rows( $db_ret );
  275. }
  276. else
  277. {
  278. // If we have done query with this class,
  279. // use last results.
  280. if( $this->_lastResult != '' )
  281. return @mysql_num_rows( $this->_lastResult );
  282. // No queries done - Throw an Exception.
  283. else
  284. throw new Exception( 'Give query return as a parameter!' );
  285. }
  286. }
  287. // ***********************************************
  288. // getLastInsertID
  289. /*!
  290. @brief Return last ID value of last INSERT INTO-query.
  291. @return ID-number. 0 if we have not created
  292. any INSERT INTO -queries with this database connection.
  293. */
  294. // ***********************************************
  295. public function getLastInsertID()
  296. {
  297. return $this->lastInsertID;
  298. }
  299. // **************************************************
  300. // queryAndAssoc
  301. /*!
  302. @brief Creates a SQL query and try to fetch
  303. results in the assoc array.
  304. @param $query SQL Query
  305. @return Array of values. If no rows, we return -1,
  306. if query failed, we return -2. Use 'query'
  307. to get more information about failed queries.
  308. */
  309. // **************************************************
  310. public function queryAndAssoc( $query )
  311. {
  312. try
  313. {
  314. $ret = $this->query( $query );
  315. if( $this->numRows( $ret ) > 0 )
  316. return $this->fetchAssoc( $ret );
  317. return -1;
  318. }
  319. catch( Exception $e )
  320. {
  321. return -2;
  322. }
  323. }
  324. // **************************************************
  325. // makeSafeForDb
  326. /*!
  327. @brief Escapes given string to be safe for database.
  328. In practice we use mysql_real_escape_string here,
  329. but this method is for more easy swapping from CSQLite
  330. class to CMySQL if required.
  331. @param $string String
  332. @return Escaped string
  333. */
  334. // **************************************************
  335. public function makeSafeForDb( $string )
  336. {
  337. return mysql_real_escape_string( $string );
  338. }
  339. }
  340. ?>