OOP MySQLi Connect [英] OOP MySQLi Connect

查看:60
本文介绍了OOP MySQLi Connect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OOP的新手.我上课数据库

Im newbie in OOP. I have class Database

class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;

function db_connect(){
    $this->host = 'localhost';
    $this->user = 'root';
    $this->pass = '';
    $this->db = 'db';

    $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->mysqli;
}

内部类数据库我具有函数db_num

Inside class Database i have function db_num

function db_num($sql){
    $num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}"));
    return $num;
}

但是当我在con参数$ this-> mysqli中使用im时,它无法连接到数据库

But it cant connect to database when im using in con argument $this->mysqli

推荐答案

混合mysqli对象样式和过程样式是不好的做法.

It is bad practice to mix mysqli object style and procedural style.

尝试一下:

function db_num($sql){
    $result = $this->mysqli->query($sql);
    return $result->num_rows;
}

在调用db_num()之前,请确保已连接到数据库,例如:

Be sure to connect to the database before you call db_num(), e.g.:

$db = new Database();
$db->db_connect();
$db->db_num("SELECT fields FROM YourTable");

在我看来,更干净的方法是在构造函数中调用db_connect:

A cleaner way in my opinion would be to call db_connect inside the constructor:

class Database{
  private $host;
  private $user;
  private $pass;
  private $db;
  public $mysqli;

  public function __construct() {
    $this->db_connect();
  }

  private function db_connect(){
    $this->host = 'localhost';
    $this->user = 'root';
    $this->pass = '';
    $this->db = 'db';

    $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->mysqli;
  }

  public function db_num($sql){
        $result = $this->mysqli->query($sql);
        return $result->num_rows;
  }
}

$db = new Database();
$db->db_num("SELECT fields FROM YourTable");

这篇关于OOP MySQLi Connect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆