博客列表 >0802接口作业

0802接口作业

杨发国的博客
杨发国的博客原创
2019年08月04日 19:14:24567浏览

实例

<?php
namespace _0802;
interface DbCrud
{
    public function create($data);
    public function read();
    public function update($data,$where);
    public function delete($where);
}
class Db implements DbCrud
{
    protected $pdo=null;
    protected $user;

    public function __construct($pdo,$username,$password,$user)
    {
       $this->pdo = new \PDO($pdo,$username,$password);
       $this->user = $user;
    }

    public function create($data)
{
    $fields = '(name,age)';
    $values = '(:name,:age)';
    $sql = 'INSERT INTO '.$this->user . $fields . ' VALUES ' . $values;
    $smpt=$this->pdo->prepare($sql);
    $smpt->execute($data);

    return
       [
       'count'=>$smpt->rowCount(),
       'id'=>$this->pdo->lastInsertId()
   ];
}
    public function read($fields = '*' , $where='', $limit = '0, 5')
{
    $where = empty($where) ? '' : ' WHERE ' . $where;
    $limit = ' LIMIT ' . $limit;
    $sql = 'SELECT '. $fields  . ' FROM ' . $this->user. $where . $limit;

    $stmt = $this->pdo->prepare($sql);
    $stmt->execute();
    return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
    public function update($data,$where)
{
    $keyArr = array_keys($data);
    $set = '';

    foreach ($keyArr as $value) {
        $set .= $value . '= :' . $value. ',';
    }
    $set =rtrim($set, ', ');

    $sql = 'UPDATE '. $this->user.' SET '.$set.' WHERE '.$where;
    $stmt = $this->pdo->prepare($sql);
    $stmt->execute($data);
    return $stmt->rowCount();


}
    public function delete($where)
{
    $sql = 'DELETE FROM '. $this->user. ' WHERE '.$where;
    $stmt = $this->pdo->prepare($sql);
    $stmt->execute();

    return $stmt->rowCount();
}

}

$dsn = 'mysql:host=127.0.0.1;dbname=php';
$username='root';
$password='root';
$user='user';

$Db= new Db($dsn, $username,$password,$user);
//$data = [
//    'name'=> '杨发国',
//    'age'=> 30,
// ];
//$res=$Db->create($data);
//echo '成功新增了'.$res['count'].'条记录'.'用户ID为'.$res['id'];
echo '<hr>';
foreach ($Db->read('id,name,age', 'age >=30') as $item) {
    print_r($item); echo '<br>';
}
echo '<hr>';
$data = [
    'name' => '作业增删改查',
    'age' => 50
];

$where = 'id = 1';
echo '成功的更新了: ' . $Db->update($data, $where) . ' 条记录';
echo '<hr>';

$where = 'id = 30';
echo '成功的删除了: ' . $Db->delete($where) . ' 条记录';

运行实例 »

点击 "运行实例" 按钮查看在线实例

2.png

 

 

5.png3.png

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议