Home > Backend Development > PHP Tutorial > PHP中封装mysql数据库链接(简单版)

PHP中封装mysql数据库链接(简单版)

WBOY
Release: 2016-06-20 12:30:51
Original
1157 people have browsed it

1,封装mysql数据链接需要哪些属性

        主机地址,数据库名,数据库密码,数据库名,字符集

2,利用构造方法在实例化类时,php底层会自动执行的特性来封装一个数据库链接类

3,在实例化类时给它传一个参数(数组),参数里面包括需要用到的数据

class Dbname{		public $host;           //主机地址,这里数据库端口默认为3306	public $user;           //数据库用户名	public $pass;           //数据库密码	public $dbname;         //数据库名	public $link;           //数据库链接名	public $char;           //字符集	public $sql;            //sql语句	public function __construct($db)	{		$this->host=$db['host'];		$this->user=$db['user'];		$this->pass=$db['pass'];		$this->dbname=$db['dbname'];		$this->char=$db['char'];		//链接数据库		$this->dbSql();		//选择数据库		$this->seleDb();		//设置字符集		$this->setChar();		//执行mysql查询语句		$this->execute_dml();	}	//链接数据库public function dbSql()	{		$this->link=mysql_connect($this->host,$this->user,$this->pass) or die('链接数据库失败');	}	//选择数据库public function seleDb()	{		mysql_select_db($this->dbname,$this->link);	}	//设置字符集public function setChar()	{		mysql_set_charset($this->char,$this->link);	}}    //执行mysql查询语句public function execute_dml($this->sql)    {        $data=array();        $res=mysql_query($this->sql);        while($row = mysql_fetch_assoc($res))        {            $data[] = $row;        }       return $data;    }
Copy after login

以上就是封装一个简单的数据库链接类,并执行一条sql查询语句返回一个数组


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template