dongwu3747 2013-06-15 12:21
浏览 32

如何保留现有的数据库连接?

I'm the developer of a PHP comments script which is designed to be included into the body of the users' websites. The script has its own database connection and currently uses the 'MySQL' extension. To make the script easier to integrate, I preserve the website's existing database connection (if there is one) by adding these two lines before connecting to the script's own connection ..

@$original_database = mysql_query('SELECT DATABASE();');
@$original_database = mysql_result($original_database, 0);

.. then after my script has finished I select the original database ..

if (!empty($original_database)) {
    @mysql_select_db ($original_database);
}

This is working fine at the moment. However many websites are (quite rightly) starting to use the newer extensions such as 'MySQLi' and 'PDO', and this makes it harder to preserve the existing database connection because for instance 'MySQLi' will complain that the connection is through 'MySQL'. Can you recommend the best way to deal with this? If it makes any difference, I plan to switch from 'MySQL' to 'MySQLi' in the near future, but obviously I will still have the same problem.

  • 写回答

1条回答 默认 最新

  • duangan2307 2013-06-15 14:30
    关注

    Always use 'MySQLi'

    function custom_mysqli_connect(){
        $GLOBALS['db_connect']=false;
        $GLOBALS['db_connect']=@mysqli_connect(HOSTNAME, USERNAME, PASSWORD);
        if($GLOBALS['db_connect']==false){
            echo("Unable to connect to the database");
        }
        if(!@mysqli_select_db($GLOBALS['db_connect'], DATABASE)){
            echo("Unable to select database");
        }
        mysqli_query($GLOBALS['db_connect'],'SET NAMES UTF8');
    }
    

    Call custom_mysqli_connect() once

    Make your queries:

    $query_1 = "SELECT * FROM table";
    
    if($results=@mysqli_query($GLOBALS['db_connect'], $query_1)){
    
       $array=array();
    
       while($result=mysqli_fetch_assoc($results)){
    
          $array[]=$result;
    
       }    
    
       mysqli_free_result($results);
    
    }
    

    When your are done

    @mysqli_close($GLOBALS['db_connect']);
    

    There is plenty of other ways to fetch the results

    mysqli_ result:: fetch_ all

    mysqli_ result:: fetch_ array

    mysqli_ result:: fetch_ assoc

    mysqli_ result:: fetch_ field_ direct

    mysqli_ result:: fetch_ field

    mysqli_ result:: fetch_ fields

    mysqli_ result:: fetch_ object

    mysqli_ result:: fetch_ row

    See: http://php.net/manual/en/mysqli.summary.php

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法