• 简单的mysql封装类


    class mysql{
    private $host;
    private $user;
    private $pwd;
    private $dbname;
    private $charset;
    private $conn=null;//保存连接的资源
    public function __construct(){
    //应该是在构造方法里读取配置文件
    //然后根据配置文件来设置私有属性
    //此处还没有配置文件,就直接赋值
    $this->host='127.0.0.1';
    $this->user='root';
    $this->pwd='';
    $this->dbname='test';
    //连接
    $this->connect($this->host,$this->user,$this->pwd);
    //切换库
    $this->switchdb($this->dbname);
    //设置字符集
    $this->setchar($this->charset);
    }
    //负责连接
    private function connect($host,$user,$pwd){
    $conn=mysql_connect($host,$user,$pwd);
    $this->conn=$conn;
    }
    //负责切换数据库,网站大的时候,可能用到不止一个库
    public function switchdb($dbname){
    $sql='use '.$dbname;
    $this->query($sql);
    }
    //负责设置字符集
    public function setchar($char){
    $sql='set names'.$char;
    $this->query($sql);
    }
    //负责发送sql查询
    public function query($sql){
    return mysql_query($sql,$this->conn);
    }
    //负责获取多行多列的select结果
    public function getall($sql){
    $list=array();
    $rs=$this->query($sql);
    if(!$rs){
    return false;
    }
    while($row=mysql_fetch_assoc($rs)){
    $list[]=$row;
    }
    return $list;
    }
    //获取一行的select结果
    public function getrow($sql){
    $rs=$this->query($sql);
    if(!$rs){
    return false;
    }
    return mysql_fetch_assoc($rs);
    }
    //获取一个单个的值
    public function getone($sql){
    $rs=$this->query($sql);
    if(!$rs){
    return false;
    }
    return mysql_fetch_row($rs);
    return $row[0];
    }
    public function close(){
    mysql_close($this->conn);
    }
    }
    $mysql=new mysql();
    print_r($mysql);

    echo '
    ';
    $sql="select*from stu";
    $arr=$mysql->getall($sql);
    var_dump($arr);

    //查询2号学员
    $sql='select*from stu where id=2';
    var_dump($mysql->getrow($sql));

    //查询共有多少个学员
    $sql='select count(*) from stu';
    var_dump($mysql->getone($sql));

  • 相关阅读:
    剑指Offer 07 重建二叉树
    剑指Offer 06 从尾到头打印链表
    剑指Offer 05 替换空格
    剑指Offer 04 二维数组中的查找
    剑指Offer 03 数组中重复的数字
    leetcode518
    leetcode474
    leetcode376
    leetcode646
    leetcode213
  • 原文地址:https://www.cnblogs.com/suiyuewuxin/p/5608487.html
Copyright © 2020-2023  润新知