Garey's Blog–FreeBSD/PHP/GoLang

十二月 15th, 2009

PHP5中的mysqli

7,467 views, MySQL, PHP, by garey.

php5提供了一种新的连接mysql的方式:mysqli。
但在网上搜索很久,没找到几个关于这个函数的中文解说,目前流行的php程序也还都是使用的mysql函数,只好自己摸索了。
先写个简单的Class,能够简单实现连接、查询,以后再慢慢完善它。

class class_mysql {
private $dbhost = ‘localhost’;
private $dbuser = ‘root’;
private $dbpasswd = ’123456′;
private $dbname = ‘testdb’;
private $link;
function __construct() {
$this->connect ();
}
function __destruct() {
$this->close ();
}
function connect(){
$this->link = new mysqli($this->dbhost, $this->dbuser, $this->dbpasswd, $this->dbname);
if (mysqli_connect_errno()) {
echo “Can’t connect to MySQL Server. Errorcode: “.mysqli_connect_error();
}
}
function query($query){
if($this->link !== false){
$mylink = $this->link;
if($result = $mylink->query($query)){
$query_result = true;
}
else {
$query_result = false;
}
}
else {
$query_result = false;
}
return $query_result;
}
function num_rows($query){
if($this->link !== false){
$mylink = $this->link;
if($result = $mylink->query($query)){
$query_result = $result->num_rows;
}
else {
$query_result = false;
}
}
else {
$query_result = false;
}
return $query_result;
}
function fetch_rows($query,&$row_num){
if($this->link !== false){
$mylink = $this->link;
if($result = $mylink->query($query)){
$row_num = $result->num_rows;
for ($i = 1; $i <= $row_num; $i++){
$query_result[$i] = $result->fetch_array(MYSQLI_ASSOC);
}
}
else {
$query_result = false;
}
}
else {
$query_result = false;
}
return $query_result;
}
function close(){
$this->link->close();
}
}

Back Top

发表评论