duanfen1312 2013-08-20 22: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-20 22: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部