A PHP class that connects to a MySQL database

Source: Internet
Author: User
Tags mysql client mysql host mysql version
  1. /*
  2. * Filename:mysql Database Connection Class
  3. * Edit bbs.it-home.org
  4. */
  5. Class mysql{
  6. Private $db _host; Database Host
  7. Private $db _user; Database user Name
  8. Private $db _pwd; Database User name password
  9. Private $db _database; Database name
  10. Private $conn; database connection identification;
  11. Private $result; The result resource ID of the Execute Query command
  12. Private $sql; SQL execution Statements
  13. Private $row; Number of entries returned
  14. Private $coding; Database encoding, gbk,utf8,gb2312
  15. Private $bulletin = true; Whether to turn on error logging
  16. Private $show _error = true; Test phase, show all errors, have security implications, default off
  17. Private $is _error = false; If the error is immediately terminated, the default is true and the recommendation is not enabled because it is very distressing for the user to see nothing when there is a problem
  18. /* Constructor function */
  19. Public function __construct ($db _host, $db _user, $db _pwd, $db _database, $conn, $coding) {
  20. $this->db_host= $db _host;
  21. $this->db_user= $db _user;
  22. $this->db_pwd = $db _pwd;
  23. $this->db_database= $db _database;
  24. $this->conn= $conn;
  25. $this->coding= $coding;
  26. $this->connect ();
  27. }
  28. /* Database connection */
  29. Public Function Connect ()
  30. {
  31. if ($this->conn== "Pconn") {
  32. Permanent links
  33. $this->conn=mysql_pconnect ($this->db_host, $this->db_user, $this->db_pwd);
  34. }else{
  35. Instant links
  36. $this->conn=mysql_connect ($this->db_host, $this->db_user, $this->db_pwd);
  37. }
  38. if (!mysql_select_db ($this->db_database, $this->conn)) {
  39. if ($this->show_error) {
  40. $this->show_error ("Database unavailable:", $this->db_database);
  41. }
  42. }
  43. mysql_query ("SET NAMES $this->coding");
  44. }
  45. /* Database execution statement, executable query add modify delete and so on any SQL statement * *
  46. Public Function query ($sql)
  47. {
  48. if ($sql = = "") {
  49. $this->show_error ("SQL statement error:", "SQL query statement is empty");}
  50. $this->sql = $sql;
  51. $result = mysql_query ($this->sql, $this->conn);
  52. if (! $result) {
  53. Used in debugging, the SQL statement is automatically printed when an error occurs
  54. if ($this->show_error) {
  55. $this->show_error ("Error SQL statement:", $this->sql);
  56. }
  57. }else{
  58. $this->result = $result;
  59. }
  60. return $this->result;
  61. }
  62. /* Create and add a new database */
  63. Public Function Create_database ($database _name) {
  64. $database = $database _name;
  65. $sqlDatabase = ' Create database '. $database;
  66. $this->query ($sqlDatabase);
  67. }
  68. /* Query server for all databases */
  69. Separate the system database from the user database for a more intuitive display?
  70. Public Function show_databases () {
  71. $rs = $this->query ("Show Databases");
  72. echo "Existing database:". $amount = $this->db_num_rows ($rs);
  73. echo "
    ";
  74. $i = 1;
  75. while ($row = $this->fetch_array ($rs)) {
  76. echo "$i $row [Database]";
  77. echo "
    ";
  78. $i + +;
  79. }
  80. }
  81. Returns all database names in the host as an array
  82. Public Function Databases ()
  83. {
  84. $rsPtr =mysql_list_dbs ($this->conn);
  85. $i = 0;
  86. $cnt =mysql_num_rows ($RSPTR);
  87. while ($i < $cnt)
  88. {
  89. $rs []=mysql_db_name ($rsPtr, $i);
  90. $i + +;
  91. }
  92. return $rs;
  93. }
  94. /* Query All tables under the database */
  95. function Show_tables ($database _name) {
  96. $this->query ("Show Tables");
  97. echo "Existing database:". $amount = $this->db_num_rows ($rs);
  98. echo "
    ";
  99. $i = 1;
  100. while ($row = $this->fetch_array ($rs)) {
  101. $columnName = "Tables_in_". $database _name;
  102. echo "$i $row [$columnName]";
  103. echo "
    ";
  104. $i + +;
  105. }
  106. }
  107. /*
  108. Mysql_fetch_row () array $row [0], $row [1], $row [2]
  109. Mysql_fetch_array () array $row [0] or $row [ID]
  110. MYSQL_FETCH_ASSOC () array is case sensitive with $row->content fields
  111. Mysql_fetch_object () object with $row[id], $row [content] field is case sensitive
  112. */
  113. /* Get Results data */
  114. Public Function Mysql_result_li ()
  115. {
  116. Return mysql_result ($STR);
  117. }
  118. /* Get Recordset, get array-Index and association, use $row[' content ' */
  119. Public Function Fetch_array ()
  120. {
  121. Return mysql_fetch_array ($this->result);
  122. }
  123. Get associative array, use $row[' field name ']
  124. Public Function Fetch_assoc ()
  125. {
  126. Return Mysql_fetch_assoc ($this->result);
  127. }
  128. Get a numeric index array, using $row[0], $row [1], $row [2]
  129. Public Function Fetch_row ()
  130. {
  131. Return mysql_fetch_row ($this->result);
  132. }
  133. Get an array of objects, using $row->content
  134. Public Function Fetch_object ()
  135. {
  136. Return Mysql_fetch_object ($this->result);
  137. }
  138. Simplify Query Select
  139. Public function FindAll ($table)
  140. {
  141. $this->query ("SELECT * from $table");
  142. }
  143. Simplify Query Select
  144. Public Function Select ($table, $columnName, $condition)
  145. {
  146. if ($columnName = = "") {
  147. $columnName = "*";
  148. }
  149. $this->query ("Select $columnName from $table $condition");
  150. }
  151. Simplified Delete del
  152. Public Function Delete ($table, $condition) {
  153. $this->query ("DELETE from $table WHERE $condition");
  154. }
  155. Simplify inserting insert
  156. Public Function Insert ($table, $columnName, $value) {
  157. $this->query ("INSERT into $table ($columnName) VALUES ($value)");
  158. }
  159. Simplified Modify Update
  160. Public Function Update ($table, $mod _content, $condition) {
  161. $this->query ("UPDATE $table SET $mod _content WHERE $condition");
  162. }
  163. /* Get the id*/from the previous INSERT operation
  164. Public Function insert_id () {
  165. return mysql_insert_id ();
  166. }
  167. Point to a data record that is determined
  168. Public Function Db_data_seek ($id) {
  169. if ($id >0) {
  170. $id = $id-1;
  171. }
  172. if (! @mysql_data_seek ($this->result, $id)) {
  173. $this->show_error ("SQL statement error:", "specified data is empty");
  174. }
  175. return $this->result;
  176. }
  177. Calculate result set bars based on select query results
  178. Public Function db_num_rows () {
  179. if ($this->result==null) {
  180. if ($this->show_error) {
  181. $this->show_error ("SQL statement error", "temporarily empty, no content!") ");
  182. }
  183. }else{
  184. Return mysql_num_rows ($this->result);
  185. }
  186. }
  187. Number of affected rows based on Insert,update,delete execution results
  188. Public Function db_affected_rows () {
  189. return Mysql_affected_rows ();
  190. }
  191. Output Display SQL statement
  192. Public Function show_error ($message = "", $sql = "") {
  193. if (! $sql) {
  194. echo "". $message. "";
  195. echo "
    ";
  196. }else{
  197. echo " ";
  198. echo " error message Tip:
    ";
  199. echo "Helvetica, Sans-serif;" > ";
  200. echo "";
  201. echo "Error number: 12142";
  202. echo "
    ";
  203. echo "Error Reason:". Mysql_error (). "

    ";
  204. echo "";
  205. echo "". $message. "";
  206. echo "";
  207. echo "
    ". $sql."
    ";
  208. $ip = $this->getip ();
  209. if ($this->bulletin) {
  210. $time = Date ("y-m-d h:i:s");
  211. $message = $message. " /r/n$this->sql "." /r/n Client IP: $ip "." /r/n time: $time "." /r/n/r/n ";
  212. $server _date=date ("y-m-d");
  213. $filename = $server _date. ". TXT ";
  214. $file _path= "error/". $filename;
  215. $error _content= $message;
  216. $error _content= "Wrong database, can not link";
  217. $file = "Error"; Settings File Save Directory
  218. Create a folder
  219. if (!file_exists ($file)) {
  220. if (!mkdir ($file, 0777)) {
  221. The default mode is 0777, which means the maximum possible access rights
  222. Die ("Upload files directory does not exist and creation failed");
  223. }
  224. }
  225. Create a txt date file
  226. if (!file_exists ($file _path)) {
  227. echo "Build date File";
  228. fopen ($file _path, "w+");
  229. The first thing to determine is that the file exists and is writable
  230. if (is_writable ($file _path))
  231. {
  232. Using Add mode to open $filename, the file pointer will be at the beginning of the file
  233. if (! $handle = fopen ($file _path, ' a '))
  234. {
  235. echo "Cannot open file $filename";
  236. Exit
  237. }
  238. Write the $somecontent to the file we opened.
  239. if (!fwrite ($handle, $error _content))
  240. {
  241. echo "Cannot write to file $filename";
  242. Exit
  243. }
  244. echo "File $filename write succeeded";
  245. echo "--the error record is saved!";
  246. Close File
  247. Fclose ($handle);
  248. } else {
  249. echo "File $filename not writable";
  250. }
  251. }else{
  252. The first thing to determine is that the file exists and is writable
  253. if (is_writable ($file _path))
  254. {
  255. Using Add mode to open $filename, the file pointer will be at the beginning of the file
  256. if (! $handle = fopen ($file _path, ' a '))
  257. {
  258. echo "Cannot open file $filename";
  259. Exit
  260. }
  261. Write the $somecontent to the file we opened.
  262. if (!fwrite ($handle, $error _content))
  263. {
  264. echo "Cannot write to file $filename";
  265. Exit
  266. }
  267. echo "File $filename write succeeded";
  268. echo "--the error record is saved!";
  269. Close File
  270. Fclose ($handle);
  271. } else {
  272. echo "File $filename not writable";
  273. }
  274. }
  275. }
  276. echo "
    ";
  277. if ($this->is_error) {
  278. Exit
  279. }
  280. }
  281. echo "";
  282. echo "
  283. ";
  284. echo "
    ";
  285. }
  286. Releasing the result set
  287. Public Function free () {
  288. @mysql_free_result ($this->result);
  289. }
  290. Database selection
  291. Public Function select_db ($db _database) {
  292. Return mysql_select_db ($db _database);
  293. }
  294. Number of query fields
  295. Public Function Num_fields ($table _name) {
  296. Return Mysql_num_fields ($this->result);
  297. $this->query ("select * from $table _name");
  298. echo "
    ";
  299. echo "Number of fields:". $total = Mysql_num_fields ($this->result);
  300. echo "
    ";
  301. for ($i =0; $i < $total; $i + +) {
  302. Print_r (Mysql_fetch_field ($this->result, $i));
  303. }
  304. echo "
  305. ";
  306. echo "
    ";
  307. }
  308. Get MySQL Server information
  309. Public Function mysql_server ($num = ") {
  310. Switch ($num) {
  311. Case 1:
  312. return Mysql_get_server_info (); MySQL Server information
  313. Break
  314. Case 2:
  315. return Mysql_get_host_info (); Get MySQL host Information
  316. Break
  317. Case 3:
  318. return Mysql_get_client_info (); Get MySQL Client Information
  319. Break
  320. Case 4:
  321. return Mysql_get_proto_info (); Get MySQL protocol Information
  322. Break
  323. Default
  324. return Mysql_get_client_info (); MySQL version information is obtained by default
  325. }
  326. }
  327. destructor, automatically shuts down the database, garbage collection mechanism
  328. Public Function __destruct ()
  329. {
  330. if (!empty ($this->result)) {
  331. $this->free ();
  332. }
  333. Mysql_close ($this->conn);
  334. }//function __destruct ();
  335. /* Get the client's real IP address */
  336. function GetIP () {
  337. if (getenv ("Http_client_ip") && strcasecmp (getenv ("Http_client_ip"), "Unknown")
  338. {
  339. $ip = getenv ("Http_client_ip");
  340. }
  341. else if (getenv ("Http_x_forwarded_for") && strcasecmp (getenv ("Http_x_forwarded_for"), "Unknown")) {
  342. $ip = getenv ("Http_x_forwarded_for");
  343. }
  344. else if (getenv ("REMOTE_ADDR") && strcasecmp (getenv ("REMOTE_ADDR"), "Unknown")
  345. {
  346. $ip = getenv ("REMOTE_ADDR");
  347. }
  348. else if (isset ($_server[' remote_addr ')) && $_server[' remote_addr '] && strcasecmp ($_server[' Remote_ ADDR '], "unknown") {
  349. $ip = $_server[' remote_addr ');
  350. }
  351. else{
  352. $ip = "Unknown";
  353. }
  354. return ($IP);
  355. }
  356. }
  357. ?>
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.