Home > php教程 > PHP源码 > body text

Php Mysql PDO

PHP中文网
Release: 2016-05-26 08:18:57
Original
1102 people have browsed it

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>";
}
Copy after login

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


Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template