duan19780629 2017-01-01 21:30
浏览 60
已采纳

避免与db类的多个mysqli连接

i just started oop and now, even very simple things seem confusing to me! this is my class for mysqli connection:

class DB{
    private $con;
    public function __construct(){
        $this->con=new mysqli('localhost','root','','dbName');
        if(!$this->con){
            echo '<b>There was a problem connecting to database! </b><br />errno: '.$con->connect_errno;
            exit;
        }
        $this->con->set_charset("utf8");
    }
    public function query($query){
        return $this->con->query($query);
    }
}

let's say i'm gonna use that like this:

$a=mysqli_real_escape_string($_POST['a']);
$b=mysqli_real_escape_string($_POST['b']);

$query='SELECT `name` FROM `someTable` WHERE `type`={'.$a.'}';
$query2='SELECT `name` FROM `someTable` WHERE `type`={'.$b.'}';

$DB = NEW DB;
$test=$DB->query($query);

$DB2 = NEW DB;
$test2=$DB2->query($query2);

i just created 2 objects from class DB. does it mean there is a new mysql connection for each object? if yes, how can i avoid it?

i know i can use mysqli_close() in __destruct() function but i read somewhere (probably in this very site :) ) that creating and destroying several mysql connections isn't good.

what should i do? p.s: beside, just as i said i'm new in oop (and mysqli as well) so if there is any comment about my class (for example did i set the charset at the right place?) i'll be honored.

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘