Blogger Information
Blog 27
fans 0
comment 0
visits 22356
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO增删改封装函数-0321作业
不乖的博客
Original
618 people have browsed it
实例
<?php
	// 作业:用PDO把增删改方法写好,可以传值
	//连接数据库
	function connect($dbname){
		$dsn = 'mysql:host=127.0.0.1;charset=utf8;port=3306;dbname=';
		$dsn .= $dbname;
		$username ='root';
		$userpsw = 'root';

		try{
			$p = new PDO($dsn,$username,$userpsw);
			echo "连接成功";
		}catch(PDOException $e){
			print_r($e->getMessage());
			exit;
		}
		return $p;
	}



	// 操作sql语句,增加一条语句
	//INSERT INTO `表名`(字段名1,字段名2)VALUE(值1,值2)
	function insert($table,$filed,$value){
		$p = connect('ouyangke');
		print_r($p);
		// $sql ="INSERT INTO `user`(`name`,`age`,`sex`,`hobby`) VALUE('啊哈2222',18,'女','编程')";

		$sql = "INSERT INTO ";
		$sql .= $table;
		$sql .=$filed;
		$sql .=' VALUE ';
		$sql .=$value;
		$a = $p->prepare($sql);
		$a->execute();
	}

	// insert("`user`","(`name`,`age`,`sex`,`hobby`)","('php中文网',18,'男','编程1+1')");



	// 修改数据
	// UPDATE 表名 SET 字段名1=值1,字段名2=值2 WHERE id =?;
	function updata($table,$filed,$where=''){
		$p = connect('ouyangke');
		print_r($p);

		// $sql="UPDATE `user` SET `name`='啊哈2222',`age` = 20 WHERE `id` = 9";
		$sql = "UPDATE";
		$sql .= $table;
		$sql .="SET";
		$sql .= $filed;
		if(!empty($where)){ //where 不可为空
			$sql .= ' WHERE ';
			$sql .= $where;
			$a = $p->prepare($sql);
			$a->execute();
		} else {
			echo 'WHERE条件不可为空,否则会修改整个数据表';
			return false;
		}
		
	}

	// updata("`user`","`name`='小仙女',`age`=22");

	// 删除数据
	// DELETE FROM 表名 WHERE id = ?
	function delete($table,$where=''){
		$p = connect('ouyangke');
		print_r($p);

		// $sql ='DELETE FROM `user` WHERE `id` = 24';
		$sql = "DELETE FROM ";
		$sql .= $table;
		if(!empty($where)){
			$sql .= "WHERE";
			$sql .= $where;
			$a = $p->prepare($sql);
			$a->execute();
		}else{
			echo "<hr>";
			echo "WHERE不能为空,否则会删除整个数据表,呆瓜";
		}
		
	}

	// delete("`user`");
	delete("`user`","`id`= 23");

?>
运行实例 »
点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post