<?php
namespace myclass;

class PdoXyz{
	//private $host="192.168.100.254";
	private $host="2280lan.dnstoo.com";
	//private $sqlUser="root";
	private $sqlUser="xyz_f";
	private $sqlPasswd="qq282246101";
	private $sqlDb="xyz";
	private $PDO=null;
	public function __construct(string $dbName=""){
		if ($dbName!="") {
			$this->sqlDb=$dbName;
		}
		$this->PDO = new \pdo("mysql:host={$this->host};port=3306;dbname={$this->sqlDb}", $this->sqlUser,$this->sqlPasswd);
		//转义交由MySQL Server转义
		$this->PDO->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
		$this->PDO->exec('set names utf8');
	}
	public function Fetch(string $sql, array $arr){
		$execute = $this->PDO->prepare($sql);
		if ($execute) {
			if($execute->execute($arr)){
				$execute->setFetchMode(\PDO::FETCH_ASSOC);
				$result = $execute->fetch();
				return $result;
			}
		}
		return null;
	}
	public function FetchAll(string $sql, array $arr) :array{
		$execute = $this->PDO->prepare($sql);
		if ($execute) {
			if($execute->execute($arr)){
				$execute->setFetchMode(\PDO::FETCH_ASSOC);
				$result = $execute->fetchAll();
				return $result;
			}
		}
		return array();
	}
	public function Exec(string $sql, array $arr):int{
		$execute = $this->PDO->prepare($sql);
		$execute->execute($arr);
		return $execute->rowCount();
	}
	public function LastInsertId(string $sql): int{
		$execute = $this->PDO->prepare($sql);
		$execute->execute();
		return $execute->lastInsertId;
	}
	public function DeleteAll(String $table): bool{
		$execute = $this->PDO->prepare("SELECT id FROM {$table}");
		if ($execute) {
			if($execute->execute(array())){
				$execute->setFetchMode(\PDO::FETCH_ASSOC);
				$a = $execute->fetchAll();
				foreach ($a as $k => $v) {
					$sql = "DELETE FROM {$table} WHERE id=?";
					$execute1 = $this->PDO->prepare($sql);
					$execute1->execute(array($v['id']));
				}
				return true;
			}
			return false;
		}
		return false;
	}
	public function __destruct(){
		$this->PDO=null;
	}
}
