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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 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-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 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' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 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.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 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

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles