对数据库操作做了一个简单的封装,简化调用。本人不太擅长php,学校老师面向对象都没讲解,自己随便封装了一个类,聊以胜无。实在不想在这里吐苦水,但是作为一个大学计算机学科老师连csdn都不知道,对于项目永远是撇开代码只看功能,连面向对象思想都没有,一学期上课整堂课都在讲库函数。观其年事已高,卖弄官腔,倚老卖老的架势,我也是无力怼之~~
对于这学期php的学习,我最大的收获还是自己不务正业时捣鼓着捞了勺渗透的汤喝了喝,真香啊。没想到php会让我在web渗透测试上有了小入门,算是点了个小技能点,不算是真正入门。不过也大致有所了解,也许等这几天忙完手上的事会写上一篇对这段时间web渗透测试学习的总结。
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019-05-17
* Time: 17:14
*/
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;
}
}
}
}