search
HomeBackend DevelopmentPHP Tutorialphp pdo encapsulation class implements mysql data addition, deletion, checking and modification

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

  279. }
  280. ?>
Copy the code


Statement
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

Global View Data Management in LaravelGlobal View Data Management in LaravelMar 06, 2025 am 02:42 AM

Laravel's View::share method offers a streamlined approach to making data accessible across all your application's views. This is particularly useful for managing global settings, user preferences, or recurring UI components. In Laravel development,

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft