把 php公用方法库中的 数据库操作函数, 重写到 Db类中。
<?php
namespace Db;
class Db
{
public $dsn;
public $name;
public $pass;
public $pdo;
public function __construct($dsn,$name,$pass)
{
$this->dsn = $dsn;
$this->name = $name;
$this->pass = $pass;
$this->connect();
}
public function connect(){
try {
$this->pdo = new \PDO($this->dsn, $this->name, $this->pass);
echo '连接成功<hr>';
} catch (\PDOException $s){
die(print_r($s->getMessage(), true));
}
return $this->pdo;
}
//增加操作
public function add($table,array $data = [])
{
$sql = "INSERT INTO {$table} SET ";
// print_r($data);
foreach ($data as $k => $v){
$sql .= '`' . $k . '`=' . "'$v'" . ',';
}
$sql = rtrim(trim($sql),',') . ';';
// echo $sql;
//创建数据库预处理对象
$sqlt = $this->pdo->prepare($sql);
//执行操作
// $sqlt->execute();
if ($sqlt->execute()){
echo '成功增加' . $sqlt->rowCount() . '条记录!' ;
}else{
echo '失败!';
}
}
//更新操作
public function update($table,$data = [],$where = '')
{
$sql = "UPDATE {$table} SET ";
foreach ($data as $k => $v){
$sql .= '`' . $k . '`=' . "'$v'" . ',';
}
$sql = rtrim(trim($sql),',');
$sql .= 'WHERE' . $where;
// echo $sql;
//创建数据库预处理对象
$sqlt = $this->pdo->prepare($sql);
//执行操作
// $sqlt->execute();
if ($sqlt->execute()){
echo '成功修改' . $sqlt->rowCount() . '条记录!' ;
}else{
echo '失败!';
}
}
//删除操作
public function delete($table,$where)
{
$sql = "DELETE FROM {$table} WHERE {$where}";
// echo $sql;
//创建数据库预处理对象
$sqlt = $this->pdo->prepare($sql);
//执行操作
// $sqlt->execute();
if ($sqlt->execute()){
echo '成功删除' . $sqlt->rowCount() . '条记录!' ;
}else{
echo '失败!';
}
}
//查询数据
public function fetch ($table,$fie,$where)
{
$sql = "SELECT {$fie} FROM {$table} WHERE {$where};";
//// echo $sql;
// var_dump($fie);
// var_dump($table);
// var_dump($where);
//创建数据库预处理对象
$stmt = $this->pdo->prepare($sql);
$find = $stmt->execute();
if ($find) {
return $stmt->fetch(PDO::FETCH_ASSOC);
} else {
return false;
}
}
}
$db = new Db('mysql:host=127.0.0.1;dbname=test1','root','root');
// $db->add('category',['name'=>'ds','alias'=>'都市生活剧']);
// $db->update('category',['name'=>'ds','alias'=>'都市生活剧'],'`cate_id`=8');
// $db->delete('category','`cate_id`=14');
$db->fetch('category','*','cate_id = 1');
// echo $fetch;