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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?