Home  >  Article  >  Backend Development  >  PHP encapsulated database addition, deletion, modification and query

PHP encapsulated database addition, deletion, modification and query

不言
不言Original
2018-05-09 09:34:124490browse

This article mainly introduces the addition, deletion, modification and query of the PHP package database. It has certain reference value. Now I share it with everyone. Friends in need can refer to it

Package:

<?php
	class mysqlSql{//封装函数
		public $db;
		public function __construct($dbname){//构造函数
			$this->db = new PDO("mysql:host=localhost;dbname=".$dbname,&#39;root&#39;,&#39;root&#39;);//数据库连接
		}
		public function zengjia($table,$title,$body){//数据库增加
			$time=time();//当前时间
			$sql = "INSERT INTO ".$table .&#39; (id,title,body,create_time)&#39;." VALUES (null,&#39;$title&#39;,&#39;$body&#39;,$time)";
			$db = $this->db;
			$row = $db->query($sql);
			return $row;

		}
		public function shanchu($table,$id){//数据库删除
			$sql = "DELETE FROM ".$table." WHERE id=".$id; 
			$db = $this->db;
			$row = $db->exec($sql);
			return $row;
		}
		public function gengxin($table,$title,$body,$id){//数据库更新
			$time=time();//当前时间
			$sql = "UPDATE ".$table." SET title=&#39;$title&#39;,body=&#39;$body&#39;,update_time=$time where id=".$id;
			$db =$this->db;
			$row = $db->exec($sql);
			return $row;
		}
		public function chaxunOne($table,$id){//数据库查询单条记录
			$sql = "SELECT * FROM ".$table." WHERE id=".$id;
			$db = $this->db;
			$sth = $db->query($sql);
			$row = $sth->fetch(PDO::FETCH_ASSOC);
			return $row;
		}
		public function chaxunAll($table){//数据库查询全部记录
			$sql = "SELECT * FROM ".$table;
			$db = $this->db;
			$sth = $db->query($sql);
			while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
				$arr[] = $row;
			}
			return $arr;
		}
	}
?>

Call:

<?php
	require "sql.php";
	$root = new mysqlSql(&#39;wanlala_1&#39;);
	//var_dump($root->chaxunAll(&#39;boke_wz&#39;));
	//var_dump($root->chaxunOne(&#39;boke_wz&#39;,2));
	//var_dump($root->zengjia(&#39;boke_wz&#39;,"是盛大发售","的飒飒是打算打算撒大大大是实打实的所说的是答案是"));
	//var_dump($root->shanchu(&#39;boke_wz&#39;,30));
	var_dump($root->gengxin(&#39;boke_wz&#39;,&#39;啊哈哈哈哈哈&#39;,&#39;尽快尽快尽快和交换机好就好&#39;,31));

?>

The above is the entire content of this article. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Simple method of encapsulating curl in PHP

Detailed explanation of PHP encapsulating Mysql operation class

The above is the detailed content of PHP encapsulated database addition, deletion, modification and query. For more information, please follow other related articles on the PHP Chinese website!

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