• 28)PHP,数据库连接类


    PHP代码展示:

     1 <?php
     2 //类名,也习惯上(推荐)使用跟文件名相似的名字
     3 //定义一个类,该类可以连接mysql数据库
     4 //并连接后返回资源(或失败就终止)
     5 class mysqlDB{
     6     public $host;
     7     public $port;
     8     public $username;
     9     public $password;
    10     public $charset;
    11     public $dbname;
    12 
    13     //连接结果(资源)
    14     static $link;
    15     
    16     //构造函数
    17     public function __construct($config){
    18         //初始化数据
    19         $this->host = isset($config['host']) ? $config['host'] : 'localhost';
    20         $this->port = isset($config['port']) ? $config['port'] : '3306';
    21         $this->username = isset($config['username']) ? $config['username'] : 'root';
    22         $this->password = isset($config['password']) ? $config['password'] : '';
    23         $this->charset = isset($config['charset']) ? $config['charset'] : 'utf8';
    24         $this->dbname = isset($config['dbname']) ? $config['dbname'] : '';
    25 
    26         //连接数据库
    27         self::$link = $this->connect();
    28         //设定连接编码
    29         $this->setCharset($this->charset);
    30         //选定数据库
    31         $this->selectDb($this->dbname);
    32     }
    33     //这里进行连接
    34     public function connect(){
    35         $link = mysql_connect("$this->host:$this->port", "$this->username","$this->password") or die("连接数据库失败!");
    36         return $link;
    37     }
    38     public function setCharset($charset){
    39         mysql_set_charset($charset, self::$link); 
    40     }
    41     public function selectDb($dbname){
    42         mysql_select_db($dbname, self::$link) 
    43     }
    44 }
    45 
    46 //先设想:
    47 $config = array(
    48     'host'=>'localhost',
    49     'port'=>'3306',
    50     'username'=>'root',
    51     'password'=>'123',
    52     'charset'=>'utf8',
    53     'dbname'=>'php34',
    54     );
    55 $link = new mysqlDB( $config );
    56 $result = $link->query("delete from tab1 where id=1");

    大概就是这个样子,我没有试,不过思路就是这个。

  • 相关阅读:
    18.12.30 【sssx】Trie图
    18.12.30 【sssx】线段树
    18.12.25 POJ 1039 Pipe
    18.12.25 POJ 3525 Most Distant Point from the Sea(半平面+二分)
    18.12.25 POJ 1228 Grandpa's Estate
    18.12.22 luogu P3047 [USACO12FEB]附近的牛Nearby Cows
    18.12.21 DSA 中缀表达式的值
    18.12.21 luogu P3650 [USACO1.3]滑雪课程设计Ski Course Design
    18.12.21 【USACO】Times17
    18.12.20 DSA Full Tank?(DP+BFS)
  • 原文地址:https://www.cnblogs.com/xiaoyoucai/p/7341754.html
Copyright © 2020-2023  润新知