今天有空写了个简单连接数据库的类:
## ***db.class.php***
~~~
<?php
class sql{
//+--------------------------
//| 连接数据库
//|
//+--------------------------
public $db;
public function linkSql($host,$user,$pass,$dbname){
if(empty($host)){
exit("连接失败,请检查输入是否有误。");
}
$this->db = @new mysqli($host,$user,$pass,$dbname);
if(@$db->connect_error){
die("连接数据库失败:".$db->connect_error);
}
}
//+--------------------------
//| 查询数据库
//|
//+--------------------------
public function query($sql){
$res = $this->db->query($sql);
if ($res == false) {
exit("Sql语句错误!请检查语句.");
}
return $res;
}
}
~~~
++------------------------------------------------------++
## ***index.php***
~~~
<?php
require_once("./db.class.php");
require_once("./db.inc.php");
$mysql = new sql();
$link = $mysql->linkSql(HOST,USER,PASS,DBNAME);
$arr = $mysql->query("select * from user");
print_r($arr);
~~~
++----------------------------------------------------++
## ***db.inc.php***
~~~
<?php
define("HOST","localhost");
define("USER","root");
define("PASS","123qwe!@#");
define("DBNAME","api");
~~~
-------2016.03.18整理