<?php
class DB{
private $link;
public function __construct($host,$user,$password,$dbname,$port)
{
$link = mysqli_connect($host,$user,$password,$dbname,$port);
if(!$link){
echo "数据库连接失败";
exit();
}
$this->link = $link;
}
//增加
public function insert($table,$data){
$sql = "";
$sql.= "insert into `$table` ";
$sql.= "(".implode(",",array_keys($data)).")";
$sql.= " VALUES";
$sql.= "('".implode("','",$data)."')";
$res = mysqli_query($this->link,$sql);
if($res && mysqli_affected_rows($this->link)>0){
return mysqli_insert_id($this->link);
}else{
return false;
}
}
//获取所有
public function getAll($sql){
$obj = mysqli_query($this->link,$sql);
$data = mysqli_fetch_all($obj,1);
return $data;
}
//删除
public function delete($table,$where){
$sql = "delete from `{$table}` where {$where}";
$res = mysqli_query($this->link,$sql);
if($res && mysqli_affected_rows($this->link)){
return mysqli_affected_rows($this->link);
}else{
return false;
}
}
//更新
public function update($table,$data,$where){
$sql = "update `$table` set";
foreach ($data as $k=>$v){
$sql .= "`{$k}` = '{$v}',";
}
$sql = rtrim($sql,',');
$sql.= $where;
$res = mysqli_query($this->link,$sql);
if($res && mysqli_affected_rows($this->link)){
return mysqli_affected_rows($this->link);
}else{
return false;
}
}
//关闭数据库连接
public function __destruct()
{
mysqli_close($this->link);
}
}
$host = '127.0.0.1';
$user = 'root';
$password = 'root';
$dbname = '1903a';
$port = '3306';
$db = new DB($host,$user,$password,$dbname,$port);
$name = $_POST['name'];
$sex = $_POST['sex'];
$age = $_POST['age'];
if(empty($name)){
echo "姓名不能为空";
exit();
}
$name_reg = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
if(!preg_match($name_reg,$name)){
echo "用户名格式不正确";
}
//增加
$data = [
'name'=> 'zhangsan',
'age' => '18',
'sex' => 1
];
//$res = $db->insert('user',$data);
//查询
//$sql = "select * from user";
//$data = $db->getAll($sql);
//删除
//$id = 9;
//$where = "id=$id";
//$res = $db->delete('user',$where);
//更新
//$data = [
// 'name'=> 'lisi',
// 'age' => 10,
// 'sex' => 2
//];
//$id = '10';
//$where = "where id=$id";
//$res = $db->update('user',$data,$where);
//var_dump($res);
?>