dongxing1853 2016-09-27 09:20
浏览 21

PHP类 - 为每个实例存储MySQL连接

I'm facing a problem which I don't know how to solve. Let's start explaining:

I've got the following class:

class MyClass{

    function MyClass($mysql_dbcon){
        $this->mysql_dbcon = $mysql_dbcon;
    }

    function execute(){
        include("myscript.php");
    }

}

myscript.php is an HTML template which uses Ajax to comunicate with other PHP scripts. Since these other PHP scripts aren't included directly in the class I'm not able to get the variable mysql_dbcon and use a different connection for each instance. Let's guess I've got the following instances:

$i1 = new Myclass($dbcon1);
$i1->execute();

$i2 = new Myclass($dbcon2);
$i2->execute();

Both instances will execute an Ajax function which call other processing scripts but these scripts can't access the instance's mysql_dbcon variable due to they're independent script executions.

How can I solve this? Is it correct to store the MySQL connection in $_SESSION so all the scripts can access it? Maybe this:

$_SESSION['instance_identifier'] = $this->mysql_dbcon;

What I want to achieve

I want to create a class in which the developer can set a MySQL connection and each instance can access to different databases so each instance will show data from different databases. The problem is the dynamic loading of that data.

Thanks in advance

  • 写回答

2条回答 默认 最新

  • dongtu4559 2016-09-27 09:27
    关注

    You cannot solve it.

    but this script can't access the instance's mysql_dbcon variable due to it's an independent script execution

    Exactly. Period. You're starting an entirely different PHP script which shares absolutely nothing with the previous script. In fact, by the time the AJAX request is initiated by the browser, the "existing" MySQL connection will already be torn down and closed since the entire PHP script has already stopped.

    "myscript.php" will simply have to open a new connection. You cannot serialise a connection into a session; it's not data which can be represented in a serialised form. This is exactly the same mechanism as any other two independent PHP files, the fact that include and AJAX are involved changes nothing.

    Also see https://stackoverflow.com/a/13840431/476

    评论

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教