<?php
header('content-type:text/html;charset=utf-8');
class Db{
public $dsn;
public $user;
public $pwd;
public $pdo;
public function __construct($dsn,$user,$pwd){
$this->dsn = $dsn;
$this->user = $user;
$this->pwd = $pwd;
$this->connect();
}
public function connect(){
$this->pdo = new PDO($this->dsn,$this->user,$this->pwd);
}
public function select($sql){
$stmt = $this->pdo->prepare($sql);
if($stmt->execute()){
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $arr;
}else{
return false;
}
}
public function find($sql){
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()){
if ($stmt->rowCount()>0){
$arr = $stmt->fetch(PDO::FETCH_ASSOC);
return $arr;
}else{
return false;
}
}else{
return false;
}
}
public function insert($sql){
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()){
if ($stmt->rowCount()>0){
return true;
}else{
return false;
}
}else{
return false;
}
}
public function update($sql){
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()){
if ($stmt->rowCount()>0){
return true;
}else{
return false;
}
}else{
return false;
}
}
public function delete($sql){
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()){
if ($stmt->rowCount()>0){
return true;
}else{
return false;
}
}else{
return false;
}
}
public function rows_count($sql){
$stmt = $this->pdo->prepare($sql);
if ($stmt->execute()){
if ($stmt->rowCount()>0){
$arr = $stmt->fetch(PDO::PARAM_INT);
$row = $arr[0];
return $row;
}else{
return false;
}
}else{
return false;
}
}
}
$db = new Db('mysql:host=localhost;dbname=demo','root','root');
$selectSql = 'SELECT * FROM `student`';
$findSql = 'SELECT * FROM `student` WHERE studentId=4';
$insertSql = 'INSERT INTO `student` SET `name`="测试",`phone`="123456",`collegeId`=3';
$updateSql = 'UPDATE `student` SET `name`="测试",`phone`="123456",`collegeId`=3 WHERE studentId=7';
$deleteSql = 'DELETE FROM `student` WHERE studentId=8';
$rowSql = 'SELECT count(*) FROM `student`';
//查询所有数据
$selectArr = $db->select($selectSql);
if ($selectArr===false){
print_r($selectArr);
}else{
echo '查找全部数据失败';
}
//查询单条数据
$findArr = $db->find($findSql);
if ($findArr===false){
print_r($findArr);
}else{
echo '查找数据失败';
}
//新增数据
$insert = $db->insert($insertSql);
if ($insert){
echo '新增成功';
}else{
echo '新增失败';
}
//修改数据
$update = $db->update($updateSql);
if ($update){
echo '编辑成功';
}else{
echo '编辑失败';
}
//删除数据
$delete = $db->delete($deleteSql);
if ($delete){
echo '删除成功';
}else{
echo '删除失败';
}
//查询总记录数
$row = $db->rows_count($rowSql);
echo '共有:'.$row.'条数据';