没有框架手写php数据库连接
```php
<?php
$db=new Db();
$data=$db->name('')->field('')->where()->select();
var_dump($data);
$db->name('')->where([''=>2])->update();
$data=$db->name('')->field('')->where()->select();
var_dump($data);
class Db{
public $hostname='';
public $username='';
public $userpwd='';
public $database='';
public $hostport='';
public $prefix='';//前缀
public $con;
public $name='';//表名
public $where='';
public $field='';
public function __construct(){
$this->con=mysqli_connect($this->hostname,$this->username,$this->userpwd,$this->database,$this->hostport);
if (!$this->con)
{
die("连接错误: " . mysqli_connect_error());
}
}
public function name($name){
$this->name=$this->prefix.$name;
return $this;
}
public function where($where){
$this->where=$where;
return $this;
}
public function get_where(){
if(empty($this->where)){
return "";
}
$where='';
foreach ($this->where as $k=>$v){
$where=$where."$k=$v";
}
return $where;
}
public function field($field){
$this->field=$field;
return $this;
}
public function get_field(){
if(empty($this->field)){
return "*";
}
return $this->field;
}
public function select(){
$where=$this->get_where();
$field=$this->get_field();
if(!empty($where)){
$where="where $where";
}
$sql="select $field from $this->name $where";
$result = $this->con->query($sql);
if ($result->num_rows > 0) {
$data=[];
while($row = $result->fetch_assoc()) {
$data[]=$row;
}
return $data;
}
return [];
}
public function find(){
$where=$this->get_where();
$field=$this->get_field();
if(!empty($where)){
$where="where $where";
}
$sql="select $field from $this->name $where";
$result = $this->con->query($sql);
if ($result->num_rows > 0) {
$data=[];
while($row = $result->fetch_assoc()) {
$data[]=$row;
}
return $data[0];
}
return [];
}
public function update($data){
$where=$this->get_where();
$data_str='';
foreach ($data as $k=>$v){
$data_str=$data_str."$k=$v";
}
if(!empty($where)){
$where="where $where";
}
$sql="UPDATE $this->name SET $data_str $where";
return $this->con->query($sql);
}
}
|