Home Backend Development PHP Tutorial php pdo encapsulation class implements mysql data addition, deletion, checking and modification

php pdo encapsulation class implements mysql data addition, deletion, checking and modification

Jul 25, 2016 am 08:51 AM

  1. define('DSN', 'mysql:host=127.0.0.1;dbname=baozhong_tour'); //Constant of database address + database name

  2. define('DB_USERNAME ', 'root'); //Database username
  3. define('DB_USERPWD', ''); //Database password
  4. ?>
  5. /**
  6. * @author shuimugan
  7. * @version 0.2
  8. * @return PDOStatement
  9. */
  10. function getConn() {
  11. try {
  12. $db = new PDO(DSN, DB_USERNAME, DB_USERPWD); //Create a pdo object and pass in the database parameter information
  13. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set database error information
  14. $db->query('set names utf8;'); //Set encoding to utf8
  15. return $db;
  16. }
  17. catch (PDOException $e) {
  18. echo 'Data processing error, please contact Website administrator!';
  19. print_r($e);//Super detailed error message, this sentence must be commented after going online!
  20. return false;
  21. }
  22. }
  23. /**
  24. * @author shuimugan
  25. * @version 0.2
  26. * @param String $tablename table name, type is string
  27. * @param Array $column_name column name, the format of the array is required
  28. * @param String $condition condition, such as 'where name=? and pws=?' or 'name like?'
  29. * @param Array $condition_value The data corresponding to the condition, the type is required to be an array, such as 'name=? and pws=?',
  30. * @return Array returns an Result set array format
  31. * @example $column_name=array('*');
  32. $condition_value=array('1');
  33. $limit='limit 0,10';
  34. $res=easy_select('user', $column_name, 'where id=? ', $condition_value,$limit);
  35. */
  36. function easy_select( $tablename,$column_name,$condition,$condition_value,$limit) {
  37. try {
  38. $db=getConn();
  39. $sql='select ';//Initialize sql statement
  40. foreach ($column_name as $col_name) {
  41. //Dynamicly append column names into sql statements
  42. if($col_name=='*'){
  43. $sql.='*';
  44. break;
  45. }
  46. if($col_name==end($column_name))
  47. {
  48. $sql.=$col_name." ";//If it is the last one, the statement does not splice comma
  49. }else {
  50. $sql.=$col_name.", ";//Splice column name + comma
  51. }
  52. }
  53. $sql.="from ".$tablename." ";//Splicing table name
  54. $sql.=$condition.' ';//Splicing conditional statement
  55. if(strlen($limit)>0){
  56. $sql.=$limit;//Splice the limit statement
  57. }
  58. $db = new PDO(DSN, DB_USERNAME, DB_USERPWD);//Create a pdo object and pass in the database parameter information
  59. $db->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//Set database error information
  60. $db->query('set names utf8;');//Set encoding to utf8
  61. $stmt = $db->prepare($sql) ;
  62. $i=1;//Start counting, calculate the number of?
  63. $j=count($condition_value);
  64. for (; $i <= $j; ) {
  65. $stmt->bindParam($i , $condition_value[$i-1]);//Bind parameters
  66. $i++;
  67. }
  68. //Query
  69. $stmt->setFetchMode(PDO::FETCH_ASSOC);//Set to get data through fields
  70. $stmt ->execute();
  71. //Get data
  72. return $stmt->fetchAll();
  73. //return $stmt->rowCount();
  74. } catch (PDOException $e) {
  75. return false;
  76. echo 'Data processing error, please contact the website administrator!';
  77. print_r($e);//Super detailed error message, this sentence must be commented after going online!
  78. }
  79. }
  80. /**
  81. * @author shuimugan
  82. * @version 0.2
  83. * @param String $tablename table name, type is string
  84. * @param Array $column_name column name, the format of the array is required
  85. * @param String $condition condition, such as 'where name=? and pws=?' or 'name like?'
  86. * @param Array $condition_value The data corresponding to the condition, the type is required to be an array, such as 'name=? and pws=?',
  87. * @return int returns the record Number of items
  88. * @example $column_name=array('*');
  89. $condition_value=array('1');
  90. $limit='limit 0,10';
  91. $res=easy_selectCount('user', $column_name , 'where id=? ', $condition_value,$limit);
  92. */
  93. function easy_selectCount($tablename,$column_name,$condition,$condition_value,$limit) {
  94. try {
  95. $db=getConn();
  96. $sql='select ';//Initialize sql statement
  97. foreach ($column_name as $col_name) {
  98. //Dynamicly append column names into sql statements
  99. if($col_name=='*'){
  100. $sql.='*';
  101. break;
  102. }
  103. if($col_name==end($ column_name))
  104. {
  105. $sql.=$col_name." ";//If it belongs to the last one, the statement does not splice the comma
  106. }else {
  107. $sql.=$col_name.", ";//Splice the column name + comma
  108. }
  109. }
  110. $sql.="from ".$tablename." ";//Splicing table name
  111. $sql.=$condition.' ';//Splicing conditional statement
  112. if(strlen($limit)> 0){
  113. $sql.=$limit;//Splicing limit statement
  114. }
  115. ;
  116. $db = new PDO(DSN, DB_USERNAME, DB_USERPWD);//Create a pdo object and pass in the database parameter information
  117. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//Set the database Error message
  118. $db->query('set names utf8;');//Set encoding to utf8
  119. $stmt = $db->prepare($sql);
  120. $i=1;//Start counting, Calculate the number of
  121. $j=count($condition_value);
  122. for (; $i <= $j; ) {
  123. $stmt->bindParam($i, $condition_value[$i-1]);/ / Bind parameters
  124. $i++;
  125. }
  126. // Query
  127. //$stmt->setFetchMode(PDO::FETCH_ASSOC);//Set to get data through fields
  128. $stmt->execute();
  129. // Get data
  130. return $stmt->rowCount();
  131. } catch (PDOException $e) {
  132. return false;
  133. echo 'Data processing error, please contact the website administrator!';
  134. print_r($e);// Super detailed error message, you must comment this sentence after going online!
  135. }
  136. }
  137. /**
  138. * @author shuimugan
  139. * @version 0.2
  140. * @param String $tablename table name, type is string
  141. * @param Array $column_name column name, the format of the array is required
  142. * @param Array $column_value corresponding data, requirements The format of the array
  143. * @return int returns the last incremented id
  144. * @example $column_name=array('pwd','ip','name');
  145. $column_value=array('1246','11.11.11.11 ','Zhang San');
  146. echo easy_insert('user',$column_name,$column_value);
  147. */
  148. function easy_insert($tablename,$column_name,$column_value) {
  149. try {
  150. $db=getConn( );
  151. $sql='INSERT INTO ';//Initialize sql statement
  152. $sql.=$tablename.' (';//Splice table name
  153. foreach ($column_name as $col_name) {
  154. //Dynamicly append column name Enter the sql statement
  155. if($col_name==end($column_name))
  156. {
  157. $sql.=$col_name." )";//If it is the last one, splice the right bracket
  158. }else {
  159. $sql.=$ col_name.", ";//Splicing column name + comma
  160. }
  161. }
  162. $sql.=' VALUES (';//Splicing $condition_value statement
  163. for ($i=0; $i < count($column_name) ; $i++) {//Splicing question marks?
  164. if ($i==count($column_name)-1) {
  165. $sql.='?) ;';
  166. }else {
  167. $sql.='?,' ;
  168. }
  169. }
  170. $db = new PDO(DSN, DB_USERNAME, DB_USERPWD);//Create a pdo object and pass in the database parameter information
  171. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);/ /Set database error information
  172. $db->query('set names utf8;');//Set encoding to utf8
  173. $stmt = $db->prepare($sql);
  174. for ($i=1; $i <= count($column_name); $i++) {//Splicing question marks?
  175. $stmt->bindParam($i, $column_value[$i-1]);
  176. }
  177. // Query
  178. // echo $sql;
  179. $stmt->setFetchMode(PDO::FETCH_ASSOC);//Set to get data through fields
  180. $stmt->execute();
  181. //Get data
  182. return $db->lastInsertId() ;
  183. } catch (PDOException $e) {
  184. return false;
  185. echo 'Data processing error, please contact the website administrator!';
  186. print_r($e);//Super detailed error message, this sentence must be commented after going online Words!
  187. }
  188. }
  189. /**
  190. * @author shuimugan
  191. * @version 0.2
  192. * @param String $tablename table name, type is string
  193. * @param Array $column_name column name, the format of the array is required
  194. * @param Array $column_value corresponding data, requirements The format of the array
  195. * @param String $condition corresponds to the where statement string such as 'where id=?'
  196. * @param Array $condition_value corresponds to where The data type of the question mark behind is required to be an array
  197. * @return int Returns the affected data Number of rows
  198. * @example $column_name=array('pwd','ip','name');
  199. $column_value=array('123456','127.152.123.132','Zhang San');
  200. $condition_value= array('1');
  201. easy_update('user',$column_name,$column_value,'where id=?',$condition_value,null);
  202. */
  203. function easy_update($tablename,$column_name,$column_value,$condition,$condition_value,$limit) {
  204. try {
  205. $db=getConn();
  206. $sql='UPDATE ';//Initialize the sql statement
  207. $sql.=$tablename.' SET ';//Splice the table name
  208. foreach ($column_name as $col_name) {
  209. //Dynamicly append the column name into the sql statement
  210. if($col_name==end($column_name))
  211. {
  212. $sql.=$col_name." = ? ";//If it belongs to the last
  213. }else {
  214. $sql.=$col_name." = ?, " ;//Splicing column name + comma
  215. }
  216. }
  217. $sql.=$condition;//Splicing conditional statement
  218. if(strlen($limit)>0){
  219. $sql.=$limit;//Splicing limit Statement
  220. }
  221. $db = new PDO(DSN, DB_USERNAME, DB_USERPWD);//Create a pdo object and pass in the database parameter information
  222. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//Set Database error message
  223. $db->query('set names utf8;');//Set encoding to utf8
  224. $stmt = $db->prepare($sql);//Prepare statement
  225. $i=1;
  226. $total=count($column_name)+count($condition_value);
  227. for (;$i <= count($column_name);) {
  228. $stmt->bindParam($i, $column_value[$i- 1]);//Bind the data parameter corresponding to the column name
  229. $i++;
  230. }
  231. $j=1;
  232. for (;$i <= $total;) {
  233. $stmt->bindParam($i, $condition_value[$j-1]);//The data parameters corresponding to the binding conditions
  234. $i++;
  235. $j++;
  236. }
  237. //Query
  238. $stmt->setFetchMode(PDO::FETCH_ASSOC);//Set to get data through fields
  239. $stmt->execute();
  240. //Get data
  241. return $stmt->rowCount() ;
  242. } catch (PDOException $e) {
  243. return false;
  244. echo 'Data processing error, please contact the website administrator!';
  245. print_r($e);//Super detailed error message, this sentence must be commented after going online Words!
  246. }
  247. }
  248. /**
  249. * @author shuimugan
  250. * @version 0.2
  251. * @param String $tablename table name
  252. * @param String $condition conditions such as 'where id= ?'
  253. * @param Array $condition_value The value corresponding to the condition is the value corresponding to ?
  254. * @param String $limit limit statement such as 'limit 0,1'
  255. * @return int Returns the number of affected results
  256. * @example $condition_value=array('83');
  257. echo easy_delete('user', 'where id =?', $condition_value, null);
  258. */
  259. function easy_delete($tablename,$condition,$condition_value,$limit) {
  260. try {
  261. $db=getConn();
  262. $sql='DELETE FROM ';//Initialize sql statement
  263. $sql.=$tablename.' ';//Splice table name
  264. $sql.=$condition;//Splice conditional statement
  265. if(strlen($limit)>0){
  266. $sql.=$limit;//Splice the limit statement
  267. }
  268. $db = new PDO(DSN, DB_USERNAME, DB_USERPWD);//Create a pdo object and pass in the database parameter information
  269. $db->setAttribute(PDO:: ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//Set database error information
  270. $db->query('set names utf8;');//Set encoding to utf8
  271. $stmt = $db->prepare($sql) ;//Prepare statement
  272. for ($i=1;$i <= count($condition_value);) {
  273. $stmt->bindParam($i, $condition_value[$i-1]);//Bind Data parameters corresponding to certain conditions
  274. $i++;
  275. }
  276. // Query
  277. $stmt->setFetchMode(PDO::FETCH_ASSOC);//Set to obtain data through fields
  278. $stmt->execute();
  279. // Get Data
  280. return $stmt->rowCount();
  281. } catch (PDOException $e) {
  282. return false;
  283. echo 'Data processing error, please contact the website administrator!';
  284. print_r($e);//Super Detailed error message, you must comment this sentence after going online!

  285. }

  286. }
  287. ?>

Copy the code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles