dpzbzp8728 2009-10-29 02:34
浏览 146
已采纳

使用mysqli对象使用php对象连接到mysql的最佳方法

If I have in my php app an object that connects to the database, lets say I am using mysqli as on object for my database transactions.

example:

$dbase = new mysqli('localhost','dbuser','dbpass','dbname');
$oresult = $dbase->query("SELECT `field` FROM `table` WHERE `otherfield` = 12;");
if($oresult->num_rows > 0) {
    $row = $oresult->fetch_row();
    $data = $row[0];
}

but I have another custom object that I want to talk to the dbase.

<?php
class Thing {
    private $sql = '';
    public $results = '';

    public function __construct($sql) {
        $this->sql = $sql;
        $this->get_data();
    }

    private function get_data() {
         // get the stuff from the dbase using $this->sql
         $this->results = 'whatever';
    }
}

$thing = new Thing("SELECT `field` FROM `table` WHERE 1");
// do whatever i want with $thing->results
?>

Where I have the '// get the stuff from the dbase using $this->sql' line i would want to connect to the dbase and get the data.

Is it best to create a new mysqli object (which i see issues with because I would need to get the connection information passed to every object I have) or can I somehow reference the object I already have by using

global $dbase

inside the get_data function.

Whats best practise?

  • 写回答

3条回答 默认 最新

  • dongyi2534 2009-10-29 02:59
    关注

    Create a wrapper class for DB connections. The wrapper could be a singleton or it could store the mysqli connection in a static field.

    class DB {
        static public $_connection;
        static function connection(...) {
            if (! self::$_connection) {
                self::$_connection = mysqli_connect(...);
            }
            return self::$_connection;
        }
    }
    

    This also makes it easy to isolate user credentials, storing them in a single script or a configuration file.

    Instead of class DB exposing the connection, you could use the DB class itself. Turn connection() into a constructor, write a prepare() method and a DBStatement class.

    class DB {
        static private $_connection;
        function __construct(...) {
            if (! self::$_connection) {
                self::$_connection = mysqli_connect(...);
            }
        }
        // returns an SQLStatement
        function prepare($query) {
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测