首页 >php教程 >PHP源码 >Php Mysql PDO

Php Mysql PDO

PHP中文网
PHP中文网原创
2016-05-26 08:18:571128浏览

Php Mysql PDO

<?php
header("Content-type:text/html; charset=utf8");

class Mysql{
	protected $mysql;
	
	function __construct(){
		$this->mysql=new PDO("mysql:host=localhost;dbname=mytest","root","root");
		if(!$this->mysql) { throw new Exception("Can&#39;t connect to Mysql");exit(0);}
		
		$this->mysql->query("set names utf8");
	}
	
	function  getItem($id){
		$result=$this->mysql->prepare("select * from table01 where id=:id");
		$result->bindParam(&#39;:id&#39;,$id,PDO::PARAM_INT);        //bindValue:不接受php参数
		$result->execute();
		
		$resultArray=array();
		while($row=$result->fetch(PDO::FETCH_ASSOC)){
			array_push($resultArray,array($row[&#39;number&#39;],$row[&#39;name&#39;]));
		}
		
		return $resultArray;
	}
	
	function removeItem($name){
		$delete=$this->mysql->prepare("delete from table01 where name=:name");
		$delete->bindParam(&#39;:name&#39;,$name,PDO::PARAM_STR);
		$delete->execute();
		
		if($delete) return true;
		else return false;
	}
	
	function addItem($number,$name){
		$insert=$this->mysql->prepare("insert into table01(number,name) values (:number,:name)");
		$insert->bindParam(&#39;:number&#39;,$number,PDO::PARAM_INT);
		$insert->bindParam(&#39;:name&#39;,$name,PDO::PARAM_STR);
		$insert->execute();
		
		if($insert) return true;
		else return false;
	}
}
try{
	$mysql=new Mysql();
	//添加条目
    if($mysql->addItem(5,"five")) echo "addItem(5,&#39;five&#39;) is success<br>";
    else echo "addItem(5,&#39;five&#39;) is wrong<br>";
	
	//删除条目
	if($mysql->removeItem("five")) echo "removeItem(&#39;five&#39;) is success<br>";
	else echo "removeItem(&#39;five&#39;) is wrong<br>";
	
	//查找条目
	$result=$mysql->getItem(1);
	echo $result[0][0]."<br>".$result[0][1];
	
}catch(Exception $e){
	echo $e->getMessage()."<br>";
}

以上就是Php Mysql PDO的内容,更多相关内容请关注PHP中文网(www.php.cn)!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn