像thinkphp,執行一個數據庫查詢操作;
~~~
D('User')->field('id,name')->where(['age'=>['lt',18]])->order('age desc')->select();
~~~
無論你是使用**pdo**或是**mysqli**還或是**其他**連接方式操作數據庫,查詢語句始終是上面那樣。
* * * * *
**數據庫接口**
~~~
interface Databases{
//數據庫連接
function connent($host,$dbname,$user,$password);
//數據庫查詢
function query($sql);
//關閉數據庫連接
function close();
}
~~~
* * * * *
**pdo連接操作數據庫**
~~~
class Pdo implements Databases{
protected $conn;//保存當前對象
function connent($host,$dbname,$user,$password)
{
// TODO: Implement connent() method.
$conn = new \PDO("mysql:dbname=$dbname;host=$host",$user,$password);
$this->conn = $conn;
return $this;
}
function query($sql)
{
// TODO: Implement query() method.
$result = $this->conn->query($sql);
$row = $result->fetch();
return $row;
}
function close()
{
// TODO: Implement close() method.
mysqli_close($this->conn);
}
}
~~~
* * * * *
**mysqli連接操作數據庫**
~~~
class Mysqli implements Databases{
protected $conn;//保存當前對象
function connent($host,$dbname,$user,$password)
{
// TODO: Implement connent() method.
$conn = mysqli_connect($host,$user,$password,$dbname);
$this->conn = $conn;
return $this;
}
function query($sql)
{
// TODO: Implement query() method.
$result = mysqli_query($this->conn,$sql);
$row = mysqli_fetch_all($result);
return $row;
}
function close()
{
// TODO: Implement close() method.
mysqli_close($this->conn);
}
}
~~~
* * * * *
**查詢操作**
~~~
//$db = new Db\Pdo();
$db = new Db\Mysqli();
$result = $db->connent('127.0.0.1','blog','root','123456')->query();
~~~