Share a self-written php class for mysql database operations

Source: Internet
Author: User
Share a self-written php class for mysql database operations
This is a Class I wrote by myself. You are welcome to discuss and guide it.
Some usage methods:
// Declare the database object
$ Conn = new Mysql;
// Load database parameters
$ Conn-> Parameter (database server, database username, database password, database name, database code, database table prefix [can be blank]);

The above code has loaded this class file and initialized some database connection parameters!
The following describes several basic methods and functions:
1. $ Conn-> Table ();
Select a data table. the parameter is the data table name.
2. $ Conn-> Field ();
Names of the selected fields separated by commas (,). if this method is not called, all fields are returned.
3. $ Conn-> Where ();
SQL Where substatement, filtering by conditions
4. $ Conn-> Order ();
SQL sorting
5. $ Conn-> Page (int );
The parameter is a positive integer. if you call this method, the record is displayed on pages.
6. $ Conn-> Select (Boolean );
Execute the query and return the query result. If yes, it is a two-dimensional array. If no, it returns false. the parameter can be omitted. if omitted, it is true by default. the returned array contains numeric elements.
7. $ Conn-> Del ();
Delete record
8. $ Conn-> Edit (array ());
Modify record. the parameter is a one-dimensional array. the array key is the field name, and the array value is the field value.
9. $ Conn-> Into (array ());
Add record. the parameter is a one-dimensional array, the array key is the field name, and the array value is the field value.

The preceding methods can be called consecutively, for example:

$ Rult = $ Conn-> Table ('user')-> Select (); // query returns all records of the user Table.
$ Rult = $ Conn-> Table ('user')-> Page (20)-> Select (); // query all records in the user Table and display them on pages, 20 entries per page;

There are a lot of methods to call and learn more!

  1. /*
  2. Database operations
  3. Operation method: Face objects
  4. Production time:
  5. Current version: BqhMysql (mysqli) 1.0.1
  6. Software author: Sad Songs
  7. Contact QQ: 36975.
  8. Contact number: 18907975647
  9. Email: admin@q128.com
  10. Contact Address: Xiaosong town, Shicheng county, Ganzhou city, Jiangxi province
  11. Zip code: 342706
  12. */
  13. Class Mysql {
  14. Private $ LocalHost = 'localhost ';
  15. Private $ LoaclUser = 'root ';
  16. Private $ LocalPass = '20140901 ';
  17. Private $ LocalBase = 'jiangxibaiyi ';
  18. Private $ LocalCode = 'utf8 ';
  19. Private $ PreFix;
  20. Private $ Conn;
  21. Private $ Start = 0;
  22. Private $ Error = false; // database connection status; false indicates no connection or the connection is abnormal
  23. Public $ Err = true; // SQL execution result
  24. Private $ Table;
  25. Private $ Field = '*';
  26. Private $ Where = '';
  27. Private $ Order = '';
  28. Private $ PageSize = 0; // display by page-> how many entries per page, 0 is not displayed by page
  29. Private $ PageCount = 1; // display by page-> Total number of items
  30. Private $ PageNum = 1; // display by page-> Total number of pages
  31. Private $ PageNo = 1; // display by page-> current page
  32. Private $ PageKey = 'page'; // PageKey
  33. Private $ PageStart = 0; // display by page-> The number of returned results starting from
  34. Private $ Select;
  35. Private $ Rest;
  36. Private $ Result = false; // Result set
  37. Public $ FormArray = array ();
  38. Public $ region _id = 0;
  39. Private $ j = 0;
  40. Public function Parameter ($ Loca, $ Root, $ Pass, $ Base, $ Code, $ PreFix = ''){
  41. $ This-> LoaclUser = $ Root;
  42. $ This-> LocalBase = $ Base;
  43. $ This-> LocalCode = $ Code;
  44. $ This-> LocalHost = $ Loca;
  45. $ This-> LocalPass = $ Pass;
  46. $ This-> PreFix = $ PreFix;
  47. Return $ this;
  48. }
  49. Private function Connection ($ SQL ){
  50. ! Function_exists (mysqli_connect )? Die ('query failed, unable to load mysqli extension'): null;
  51. $ This-> Conn = @ new mysqli ($ this-> LocalHost, $ this-> LoaclUser, $ this-> LocalPass, $ this-> LocalBase );
  52. $ This-> Error = mysqli_connect_errno () = 0? True: false;
  53. ! $ This-> Error? Die ('database connection error, check database connection parameters'): null;
  54. $ This-> Conn-> query ('set names'. $ this-> LocalCode );
  55. $ This-> Rest = $ this-> Conn-> query ($ SQL );
  56. $ This-> Err = mysqli_error ($ this-> Conn );
  57. $ This-> consumer _id = mysqli_insert_id ($ this-> Conn );
  58. $ This-> Rest-> free_result;
  59. $ This-> Conn-> close;
  60. $ This-> FormArray = '';
  61. Return $ this;
  62. }
  63. Public function null (){
  64. $ This-> PageSize = 0;
  65. // $ This-> PageCount = 1;
  66. $ This-> PageStart = 1;
  67. $ This-> Field = '*';
  68. $ This-> Select = '';
  69. Unset ($ this-> Table, $ this-> Where, $ this-> Order, $ this-> Result );
  70. }
  71. Public function Table ($ TableName) {// data Table
  72. $ This-> null ();
  73. $ This-> Table = '''. $ this-> PreFix. $ TableName .''';
  74. Return $ this;
  75. }
  76. Public function Field ($ Array = '*') {// data Field
  77. ! Empty ($ this-> Field )? $ This-> Field = '': null;
  78. $ Array = explode (',', $ Array );
  79. Foreach ($ Array as $ field ){
  80. $ This-> Field. =! $ This-> Start? '''. $ Field. ''': ', ''. $ field .''';
  81. $ This-> Start ++;
  82. }
  83. $ This-> Start = 0;
  84. Return $ this;
  85. }
  86. Public function Where ($ Where) {// condition
  87. $ This-> Where = 'where'. $ where;
  88. Return $ this;
  89. }
  90. Public function Order ($ Order) {// sort
  91. $ This-> Order = 'Order by'. $ order;
  92. Return $ this;
  93. }
  94. Public function pk ($ key) {// pagination url parameter key
  95. $ This-> PageKey = $ key;
  96. Return $ this;
  97. }
  98. Public function Page ($ PageSize) {// Page
  99. $ This-> PageSize = $ PageSize;
  100. $ This-> PageNo = $ this-> get ($ this-> PageKey );
  101. $ This-> PageNo = empty ($ this-> PageNo) |! Isset ($ this-> PageNo) |! Is_numeric ($ this-> PageNo) | $ this-> PageNo <1? 1: $ this-> PageNo;
  102. Return $ this;
  103. }
  104. Public function post ($ Key, $ Filter = true ){
  105. Return $ Filter? Strip_tags ($ _ POST [$ Key]): $ _ POST [$ Key];
  106. }
  107. Public function get ($ Key, $ Filter = true ){
  108. Return $ Filter? Strip_tags ($ _ GET [$ Key]): $ _ GET [$ Key];
  109. }
  110. Public function Sel (){
  111. $ This-> Select = 'select'. $ this-> Field. 'from'. $ this-> Table. $ this-> Where. $ this-> Order;
  112. $ This-> Connection ($ this-> Select );
  113. If ($ this-> Rest-> num_rows ){
  114. While ($ Rs = $ this-> Rest-> fetch_assoc ()){
  115. $ This-> Result [] = $ Rs;
  116. }
  117. }
  118. $ DataBase = $ this-> Result;
  119. Return empty ($ DataBase )? False: $ DataBase;
  120. }
  121. Public function querys ($ SQL = '', $ Type = 'not', $ biao = false ){
  122. $ This-> Select = $ SQL;
  123. $ This-> Connection ($ this-> Select );
  124. If ($ this-> Rest-> num_rows ){
  125. If (! $ Biao ){
  126. While ($ Rs = $ this-> Rest-> fetch_array ()){
  127. $ This-> Result [] =! Preg_match ('/^ \ d + $/I', $ Type )? $ Rs: $ Rs [$ Type];
  128. }
  129. } Else {
  130. While ($ Rs = $ this-> Rest-> fetch_assoc ()){
  131. $ This-> Result [] = $ Rs;
  132. }
  133. }
  134. }
  135. $ DataBase = $ this-> Result;
  136. Return empty ($ DataBase )? False: $ DataBase;
  137. }
  138. Public function executes ($ SQL = ''){
  139. $ This-> Connection ($ SQL );
  140. Return $ this-> Rest;
  141. }
  142. Public function exists ($ T = '', $ F ='', $ W = ''){
  143. If (empty ($ F) {return 0 ;}
  144. $ Cmd = empty ($ W )? 'Select sum ('. $ F. ') as 'policyinum' from ''. $ this-> PreFix. $ T. ''': 'Select sum ('. $ F. ') as 'policyinum' from ''. $ this-> PreFix. $ T. ''where '. $ W;
  145. $ This-> Connection ($ cmd );
  146. Unset ($ T, $ F, $ W, $ cmd );
  147. $ Rel = $ this-> Rest-> fetch_array ();
  148. Return round ($ Rel ['categoryinum'], 2 );
  149. }
  150. Public function ExistsTo ($ Bili = 10000, $ T = '', $ F ='', $ W = ''){
  151. If (empty ($ F) {return 0 ;}
  152. $ Cmd = empty ($ W )? 'Select sum ('. $ F. ') as 'policyinum' from ''. $ this-> PreFix. $ T. ''': 'Select sum ('. $ F. ') as 'policyinum' from ''. $ this-> PreFix. $ T. ''where '. $ W;
  153. $ This-> Connection ($ cmd );
  154. Unset ($ T, $ F, $ W, $ cmd );
  155. $ Rel = $ this-> Rest-> fetch_array ();
  156. Return round ($ Rel ['policyinum'] * $ Bili );
  157. }
  158. Public function Select ($ Type = true, $ ListNum = 1) {// return record (array format, number of returned Records)
  159. $ This-> Select = 'select'. $ this-> Field. 'from'. $ this-> Table. $ this-> Where. $ this-> Order;
  160. If (is_numeric ($ ListNum )){
  161. If ($ this-> PageSize> 0 ){
  162. $ This-> Connection ($ this-> Select); // execute the query
  163. $ This-> PageCount = $ this-> Rest-> num_rows; // gets the total number of records.
  164. $ This-> PageNum = ceil ($ this-> PageCount/$ this-> PageSize); // total number of pages
  165. $ This-> PageNo = $ this-> PageNo> $ this-> PageNum? $ This-> PageNum: $ this-> PageNo;
  166. $ This-> PageStart = ($ this-> PageNo-1) * $ this-> PageSize; // The number of items returned from the current start
  167. $ This-> Select. = 'limit'. $ this-> PageStart. ','. $ this-> PageSize; // re-construct an SQL statement
  168. } Else {
  169. $ This-> Select. = 'limit '. $ ListNum; // reconstructs an SQL statement.
  170. }
  171. } Else {
  172. $ This-> Select. = 'limit 1'; // reconstructs an SQL statement.
  173. }
  174. // Echo $ this-> Select;
  175. $ This-> Connection ($ this-> Select); // run the query again
  176. If ($ this-> Rest-> num_rows) {// if the record exists
  177. If ($ Type ){
  178. While ($ Rs = $ this-> Rest-> fetch_array ()){
  179. $ This-> Result [] = $ Rs;
  180. }
  181. } Else {
  182. While ($ Rs = $ this-> Rest-> fetch_assoc ()){
  183. $ This-> Result [] = $ Rs;
  184. }
  185. }
  186. }
  187. If ($ ListNum = 1 or! Is_numeric ($ ListNum ))&&! $ This-> PageSize) {$ this-> Result = $ this-> Result [0];}
  188. $ DataBase = $ this-> Result;
  189. Return empty ($ DataBase )? False: $ DataBase;
  190. }
  191. Public function Num () {// total number of returned Records
  192. $ This-> Select = 'select'. $ this-> Field. 'from'. $ this-> Table. $ this-> Where. $ this-> Order;
  193. $ This-> Connection ($ this-> Select); // execute the query
  194. Return $ this-> Rest-> num_rows; // Retrieve the total number of records
  195. }
  196. Public function PageNav ($ NumNav = false) {// pagination
  197. $ Action = $ this-> get ('action ');
  198. ! Empty ($ Action) or $ Action = 'index ';
  199. $ Module = $ this-> get ('module ');
  200. ! Empty ($ Module) or $ Module = 'index ';
  201. $ NavUrl = '/'. $ Module. '/'. $ Action. '/'. $ this-> PageKey .'/';
  202. $ NaIndex = '/'. $ Module. '/'. $ Action;
  203. $ PageHtml = "\ n

    ";

  204. $ PageHtml. = ''. $ this-> PageCount. 'record '. $ this-> PageNo.'/'. $ this-> PageNum. 'page ';
  205. $ This-> PageNo <= 1 or $ PageHtml. = "homepage \ nPageNo-1)." \ "> Previous Page \ n ";
  206. If ($ NumNav) {$ PageHtml. = $ this-> NumPage ($ NavUrl );}
  207. $ This-> PageNo >=$ this-> PageNum or $ PageHtml. = "PageNo + 1 ). "\"> Next Page \ nPageNum. "\"> Last Page \ n ";
  208. $ PageHtml. ="

    \ N ";
  209. Return $ PageHtml;
  210. }
  211. Private function NumPage ($ Can = '') {// numeric page
  212. $ NumHtml = '';
  213. $ First = 1;
  214. $ Last = $ this-> PageNum;
  215. If ($ this-> PageNum> 5 ){
  216. If ($ this-> PageNo <$ this-> PageNum ){
  217. $ First = $ this-> PageNo-2;
  218. $ Last = $ this-> PageNo + 2;
  219. } Else {
  220. $ First = $ this-> PageNo-4;
  221. $ Last = $ this-> PageNum;
  222. }
  223. }
  224. If ($ First <1) {$ First = 1; $ Last = $ First + 4 ;}
  225. If ($ Last> $ this-> PageNum) {$ First = $ this-> PageNum-4; $ Last = $ this-> PageNum ;}
  226. For ($ I = $ First; $ I <= $ Last; $ I ++ ){
  227. $ NumHtml. = $ this-> PageNo! = $ I? "\ N \ t ". ''. $ I. ''. "\ n \ t": "\ n \ t ". ''. $ I. ''. "\ n \ t ";
  228. }
  229. Unset ($ Can, $ First, $ I, $ Last );
  230. Return $ NumHtml;
  231. }
  232. Public function UserPage ($ NumNav = false, $ PageName = 'index', $ Mulu = 'user') {// Member Center page
  233. $ NavUrl = '/'. $ Mulu. '/'. $ PageName. '/'. $ this-> PageKey .'/';
  234. $ PageHtml = "\ n

    ";

  235. $ PageHtml. = ''. $ this-> PageCount. 'record '. $ this-> PageNo.'/'. $ this-> PageNum. 'page ';
  236. $ This-> PageNo <= 1 or $ PageHtml. = "homepage \ nPageNo-1)." \ "> Previous Page \ n ";
  237. If ($ NumNav) {$ PageHtml. = $ this-> NumPage ($ NavUrl );}
  238. $ This-> PageNo >=$ this-> PageNum or $ PageHtml. = "PageNo + 1 ). "\"> Next Page \ nPageNum. "\"> Last Page \ n ";
  239. $ PageHtml. ="

    \ N ";
  240. Return $ PageHtml;
  241. }
  242. // Form processing starts
  243. // Submit when judging the form
  244. Public function FormIs ($ Keys = 'mm '){
  245. Return $ _ POST [$ Keys] = 1? True: false;
  246. }
  247. // Obtain data in post mode
  248. Public function _ post ($ Keys = '', $ TiHuan = ''){
  249. $ Values = strip_tags ($ _ POST [$ Keys]);
  250. $ This-> FormArray [$ Keys] = empty ($ Values )? $ TiHuan: $ Values;
  251. Return empty ($ Values )? $ TiHuan: $ Values;
  252. }
  253. // Get the data
  254. Public function _ get ($ Keys = '', $ TiHuan = ''){
  255. $ Values = strip_tags ($ _ GET [$ Keys]);
  256. Return empty ($ Values )? $ TiHuan: $ Values;
  257. }
  258. // Determine whether the value is a number and not less than 0
  259. Public function IsNum ($ Num = 0, $ Mesg = 'parameter must be a number '){
  260. If (is_numeric ($ Num )&&! Empty ($ Num) & $ Num> = 0 ){
  261. Return $ Num;
  262. } Else {
  263. Die ($ Mesg );
  264. }
  265. }
  266. // Returns True/False if it is a number and is not less than 0.
  267. Public function NumBer ($ Num = 0 ){
  268. Return is_numeric ($ Num )&&! Empty ($ Num) & $ Num> = 0? True: false;
  269. }
  270. // Detection data seems to exist
  271. Public function IsData ($ Types = true, $ memg = 'data already exists '){
  272. $ This-> Connection ('select'. $ this-> Field. 'from'. $ this-> Table. $ this-> Where );
  273. If ($ Types ){
  274. $ This-> Rest-> num_rows> 0? Die ($ memg): null;
  275. } Else {
  276. Return $ this-> Rest-> num_rows;
  277. }
  278. }
  279. // Write database records
  280. Public function into ($ Mesg = ''){
  281. ! Is_array ($ this-> FormArray )? Die ($ Mesg): null;
  282. $ SQL = 'insert'. $ this-> Table .'('';
  283. $ I = 0;
  284. Foreach ($ this-> FormArray as $ Key => $ Val ){
  285. $ Duan. =! $ I? $ Key. ''': ', ''. $ Key .''';
  286. If (is_numeric ($ Val )){
  287. $ Vals. =! $ I? $ Val: ','. $ Val;
  288. } Else {
  289. $ Vals. =! $ I? '\ ''. $ Val.' \'': ', \ ''. $ Val .'\'';
  290. }
  291. $ I ++;
  292. }
  293. $ SQL. = $ Duan. ') values ('. $ Vals .')';
  294. // @ File_put_contents ('1. SQL ', $ SQL, FILE_APPEND );
  295. $ This-> Connection ($ SQL );
  296. Return! Empty ($ this-> Err )? False: true;
  297. }
  298. // Write data in array form
  299. Public function MsgBox ($ Table = '', $ Filed = array ()){
  300. $ This-> Table ($ Table );
  301. Foreach ($ Filed as $ Key => $ Val ){
  302. $ This-> FormArray [$ Key] = $ Val;
  303. }
  304. Return $ this-> Into ('data not obtained ');
  305. }
  306. // Modify database records
  307. Public function Edit ($ Array = array ()){
  308. If (empty ($ Array) {$ Array = $ this-> FormArray ;}
  309. If (! Is_array ($ Array) | empty ($ Array )){
  310. Return false;
  311. } Else {
  312. $ SQL = 'update'. $ this-> Table. 'set ';
  313. $ I = 0;
  314. $ Sub = '';
  315. $ Huan = array ('-' => '[jian]', '+' => '[jia]', '*' => '[cheng]', '/' => '[chu]');
  316. $ Zhan = array ('[jian]' => '-', '[jia]' => '+', '[cheng]' => '*', '[chu]' => '/');
  317. Foreach ($ Array as $ Files => $ Val ){
  318. $ Val =! Is_numeric ($ Val )&&! Preg_match ('/\' \ w + \ '\ s * (\ + | \-| \ * | \/)/I', $ Val )? '\ ''. $ Val.' \'': $ Val;
  319. Foreach ($ Huan as $ key => $ val ){
  320. $ Val = str_replace ($ key, $ val, $ Val );
  321. }
  322. $ Duan =! $ I? '''. $ Files. ''= ':',''. $ Files. ''= ';
  323. $ Sub. = $ duan. $ Val;
  324. $ I ++;
  325. }
  326. $ SQL. = $ Sub. $ this-> Where;
  327. Foreach ($ Zhan as $ Fan =>$ Hui ){
  328. $ SQL = str_replace ($ Fan, $ Hui, $ SQL );
  329. }
  330. // Echo $ SQL; die;
  331. $ This-> Connection ($ SQL );
  332. Unset ($ Array, $ duan, $ Fan, $ Files, $ Huan, $ Hui, $ I, $ key, $ SQL, $ Sub, $ Val, $ Zhan, $ val );
  333. Return! Empty ($ this-> Err )? False: true;
  334. }
  335. }
  336. // Delete database records
  337. Public function del (){
  338. $ SQL = 'delete from'. $ this-> Table. $ this-> Where;
  339. $ This-> Connection ($ SQL );
  340. Unset ($ SQL );
  341. Return! Empty ($ this-> Err )? False: true;
  342. }
  343. // Form processing ends
  344. // Page jump
  345. Public function Msg ($ Text = 'Operation succeeded '){
  346. Echo' ';
  347. Echo'

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.