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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?