class DBHelper
{
private $host = "localhost";
private $username = "root";
private $password = "xxxxxxx";
private $database = "phpstudy";
private $connection;
function __construct()
{
}
private function getConnection()
{
return $this->connection;
}
private function openConnection(){
$this->connection = new mysqli($this->host,$this->username,$this->password,$this->database);
}
private function closeConnection(){
$this->connection->close();
}
// 查找
public function select($sql,$type_str=null,$params=null){
$this->openConnection();
$conn = $this->getConnection();
if ($type_str!=null || $params!=null) {
// 构造$stmt->bind_param参数
$stmt = $conn->prepare($sql);
$arr = array();
$arr[] = $type_str;
for ($i = 0; $i < count($params);$i++) {
$arr[] = &$params[$i];
}
// 回调
call_user_func_array(array($stmt,'bind_param'), $arr);
$stmt->execute();
$meta = $stmt->result_metadata();
$result_params = array();
while ($field = $meta->fetch_field()){
$result_params[] = &$row[$field->name];
}
call_user_func_array(array($stmt,'bind_result'),$result_params);
while($stmt->fetch()){
foreach ($row as $key=>$val){
$c[$key] = $val;
}
$result[] = $c;
}
$stmt->free_result();
$this->closeConnection();
return $result;
}else{
$result = $conn->query($sql);
$rel = array();
while ($row = $result->fetch_assoc()){
$rel[] = $row;
}
$result->free_result();
$this->closeConnection();
return $rel;
}
}
// 增、删、改操作
public function IUDoption($sql,$type_str=null,$params=null){
$this->openConnection();
$conn = $this->getConnection();
if ($type_str!=null || $params!=null) {
$stmt = $conn->prepare($sql);
$arr = array();
$arr[] = $type_str;
for ($i = 0; $i < count($params);$i++) {
$arr[] = &$params[$i];
}
call_user_func_array(array($stmt,'bind_param'), $arr);
$res = $stmt->execute();
if ($res){
$stmt->free_result();
$this->closeConnection();
return true;
}else{
$stmt->free_result();
$this->closeConnection();
return false;
}
}else{
$res = $conn->query($sql);
if ($res){
$res->free_result();
$this->closeConnection();
return true;
}else{
$res->free_result();
$this->closeConnection();
return false;
}
}
}
}
打赏

感谢支持与鼓励~