duanfen1312 2013-08-21 06:43
浏览 12
已采纳

为PDO和mysql_xxx使用一个数据库连接

I'm using PDO in a website, now I need a php class that uses mysql_xxx functions. It doesn't connect and select db itself, you should use it like this:

    if (!($connection = @mysql_connect($MySQL_host, $MySQL_user, $MySQL_pass))) {
        die('Error connecting to the database!');        }
    if (!@mysql_select_db($MySQL_database, $connection)) {
        die('Error selecting database!');                }

    require '../Zebra_Mptt.php';
    $mptt = new Zebra_Mptt();
    $foo = $mptt->add(0, 'Foo');

Can I create and share a connection between PDO and mysql_ functions or anything more efficient?

  • 写回答

2条回答 默认 最新

  • drodsh7940 2013-08-21 06:52
    关注

    Can I create and share a connection between PDO and mysql_ functions

    No, such a feature is not available with PHP.

    or anything more efficient?

    Sure. The efficient way is to program against interfaces. The Zebra_Mptt library should define an interface for the database adapter it uses so that you can replace it with one that is re-using your database connection.

    As it currently doesn't, you would need to refactor it, encapsulate the database interaction calls into the standard database connection object for that library, then extract the interface of that connection object and then create your PDO variant and inject it instead.

    I just took a brief look, the class is rather straight forward so this should be merely straight forward. All it does is firering some SQL queries and in the very beginning checking if the database is online which you can easily map and defer.

    In case you don't want to do that, you can take a pre-existing wrapper for the mysql_* interface, either replace the prefix in the existing library or just disable the mysql extension and then let it create the functions based on PDO. Such a wrapper is here:

    Usage:

    <?php
    require('/path/to/mysqlpdo.php');
    
    mysqlpdo::createfunctions('mysql');
    

    It will need an additional mysql_ping() and mysql_real_escape_string() wrapped to have it work though, but this should be easily feasibile, but nothing is perfect in that field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ue5运行的通道视频都会有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数