zoukankan      html  css  js  c++  java
  • 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");

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

  • 相关阅读:
    作业
    剑指Offer:链表中倒数第k个节点
    剑指Offer:反转链表
    剑指Offer:数值的整数次方
    剑指Offer:剪绳子Ⅰ和剪绳子Ⅱ
    剑指Offer:机器人的运动范围
    Linux下进程与线程的区别
    剑指Offer:调整数组顺序使奇数位于偶数前面
    剑指Offer:删除链表的节点
    剑指Offer:打印从1到最大的n位数
  • 原文地址:https://www.cnblogs.com/xiaoyoucai/p/7341754.html
Copyright © 2011-2022 走看看