dsfs587465 2012-12-20 14:56
浏览 43
已采纳

调用一个方法用mysqli连接到数据库

Hi i am trying to move from MySQL to MySQLi in my PHP script, i had this system class with the function that connects to the database that i call whenever i need, with a simple method like this:

Sys::database_connect();

the actual code of the function is:

function database_connect(){
    require 'conf.php';//configuration file with database variables (sql_)
    mysql_connect($sql_serv, $sql_user, $sql_pw) OR die('ERRO!!! não ligou a base de dados');
    mysql_select_db($sql_bd);
}

after calling the function i can query the database without problem.

But I cant do the same with mysqli if I put this in the sys class:

function database_connect(){
    require 'conf.php';

    $mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
        if (mysqli_connect_errno()) {
        printf("Ligação à Base de dados falhou: %s
", mysqli_connect_error());
        exit();
    }
}

When I call Sys::database_connect();

it connects to the database but i can't query has i used to what i would like would be a simple method as I have done with normal MySQL, if somebody can explain what am I doing wrong or why exactly I cannot do it like that...

Thank you in advance; Fernando Andrade.

  • 写回答

2条回答 默认 最新

  • duan2428 2012-12-20 15:02
    关注

    Your later queries have to use the mysqli connection identifier, you create when connecting to the database. So save this to a property of your system class and use it later on.

    function database_connect(){
        require 'conf.php';
    
        $mysqli = new mysqli($sql_serv, $sql_user, $sql_pw, $sql_bd);
        if (mysqli_connect_errno()) {
            printf("Ligação à Base de dados falhou: %s
    ", mysqli_connect_error());
            exit();
        }
    
        Sys::$dbConn = $mysqli;
    }
    

    and then later on

    function query( $sql ) {
        Sys::$dbConn->query( $sql );
        // error handling etc.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀