php 类的写法//Db.class.php
class Db {
private $_dblink;
public $result;
public function __construct($host, $user, $password, $dbname, $charset = 'utf8') {
try{
if($this->_dblink = mysql_connect($host, $user, $password)) {
if(mysql_select_db($dbname)) {
$this->query("SET NAMES " . $charset . " ;");
} else {
throw new Exception(mysql_error());
}
} else {
throw new Exception(mysql_error());
}
} catch (Exception $e) {
die($e->getMessage());
}
}
public function query($sql) {
return $this->result = mysql_query($sql);
}
public function fetch() {
return mysql_fetch_array($this->result);
}
public function fetchAll() {
$rs = array();
$rsAll = array();
while($rs = mysql_fetch_array($this->result)) {
$rsAll[] = $rs;
}
return $rsAll;
}
public function __destruct() {
mysql_close($this->_dblink);
}
}
复制PHP内容到剪贴板PHP代码:
//test.php
$db = new Db('localhost', 'root', '', 'hent_qxoa');
$db->query("SELECT * FROM qx_user ;");
var_dump($db->fetchAll());