在WEB开发中php连接mysql数据库是肯定会用到的,如果你不会连接数据库就等不会WEB,我们提供这一款连接mysql数据库的类文件,可以方便快捷使php与mysql建立连接,代码如下:
- * created on 2010-4-21
- *
- * the class for control mysql
- *
- * made by s71ence
- *
- * @$host
- * @$user_name
- * @$user_pwd
- * @$data_base
- * @$coding
- */
- class mysql
- {
- private $host;
- private $user_name;
- private $user_pwd;
- private $data_base;
- private $coding;
-
- function __construct($host,$user_name,$user_pwd,$data_base,$coding)
- {
- $this->host=$host;
- $this->user_name=$user_name;
- $this->user_pwd=$user_pwd;
- $this->data_base=$data_base;
- $this->coding=$coding;
- $this->connect();
- }
-
-
-
-
-
- function connect()
- {
- $link=mysql_connect($this->host,$this->user_name,$this->user_pwd) or die($this->error());
- mysql_select_db($this->data_base,$link) or die("无法连接数据库".$this->data_base);
- mysql_query("set names '$this->coding'");
- }
-
- function error()
- {
- return mysql_error();
- }
-
- function query($sql, $type = '')
- {
- if(!($query = mysql_query($sql)))
- {
- $this->show('say:', $sql);
- }
-
- return $query;
- }
-
- function show($message = '', $sql = '')
- {
- if(!$sql)
- {
- echo $message;
- }
- else
- {
- echo $message.'<br>'.$sql;
- }
- }
-
- function affected_rows()
- {
- return mysql_affected_rows();
- }
-
- function result($query, $row)
- {
- return mysql_result($query, $row);
- }
-
- function num_rows($query)
- {
- return @mysql_num_rows($query);
- }
-
- function num_fields($query)
- {
- return mysql_num_fields($query);
- }
-
- function free_result($query)
- {
- return mysql_free_result($query);
- }
-
- function insert_id()
- {
- return mysql_insert_id();
- }
-
- function fetch_row($query)
- {
- return mysql_fetch_row($query);
- }
-
- function version()
- {
- return mysql_get_server_info();
- }
-
- function fetch_array($result)
- {
- return mysql_fetch_array($result);
- }
-
- function close()
- {
- return mysql_close();
- }
-
-
-
-
-
-
-
-
-
-
-
- function fn_insert($table,$fields,$values)
- {
- return $this->query("insert into $table ($fields) values ($values)");
- $this->close();
- }
-
-
-
-
-
-
-
-
-
- function fn_select($table,$fields,$condition,$order,$limit)
- {
- $query="select $fields from $table";
- if($condition!="")
- {
- $query.=" where $condition";
- }
- if($order!="")
- {
- $query.=" order by $order ";
- }
- if($limit!="")
- {
- $query.=" limit $limit";
- }
- return $this->query($query);
- $this->close();
- }
-
-
-
-
-
-
-
- function fn_delete($table,$condition)
- {
- return $this->query("delete from $table where $condition");
- $this->close();
- }
-
-
-
-
-
-
-
- function fn_update($table,$set,$condition)
- {
- $sql="update $table set $set";
- if($condition!="")
- {
- $sql.=" where $condition";
- }
- return $this->query($sql);
- $this->close();
- }
-
-
-
-
- function __destruct()
- {
-
- }
- }
调用方法,代码如下:
$db = new mysql('127.0.0.1','username','password','databasename',"utf8"); |