PHP函数无法连接到数据库以调用查询

时间:2015-03-31 09:26:40

标签: php mysql mysqli

我有三个.php个文件。

db_conx.php

$db_conx = mysqli_connect("localhost", "admin", "admin", "gestiune");
    // Evaluate the connection
    if (mysqli_connect_errno()) {
        echo mysqli_connect_error();
        exit();
}

的functions.php

function deplata($pid){
        $sqlp = "SELECT * FROM plati WHERE user_id";
        $queryp = mysqli_query($db_conx, $sqlp);
        $type = "day";
        $payments = 0;
        $salary = 80;
        $days = 4;
        $topay = 0;
        while($getplata = mysqli_fetch_assoc($queryp)){
            $plati += $getplata['valoare'];
        }
        if($tip == "day"){
            $topay = $days * $salary;
        }

        return $topay;
}

我有index.php文件来调用文件并使用它们。

include_once("php_includes/db_conx.php");
include_once("php_includes/functii.php");

$salariu = deplata(5);
echo $salariu;

问题是它不会连接到数据库并返回一些错误:

  

注意:未定义的变量:db_conx in   第5行的D:\ xampp \ htdocs \ manager \ pages \ php_includes \ functions.php

     

警告:mysqli_query()期望参数1为mysqli,null给定   在第5行的D:\ xampp \ htdocs \ manager \ pages \ php_includes \ functions.php

     

警告:mysqli_fetch_assoc()期望参数1为mysqli_result,   在D:\ xampp \ htdocs \ manager \ pages \ php_includes \ functions.php中给出null   在第11行

然后它打印该值(因为它当前不使用数据库任何值)。 我尝试了什么:我尝试将functions.php内容直接放入index.php文件中,我尝试调用db_conx.php文件中的functions.php文件。

1 个答案:

答案 0 :(得分:3)

您需要在function.php中定义值。结帐以下代码

<强> function.php

function deplata($pid){

   global $db_conx;

    $sqlp = "SELECT * FROM plati WHERE user_id";
    $queryp = mysqli_query($db_conx, $sqlp);
    $type = "day";
    $payments = 0;
    $salary = 80;
    $days = 4;
    $topay = 0;
    while($getplata = mysqli_fetch_assoc($queryp)){
        $plati += $getplata['valoare'];
    }
    if($tip == "day"){
        $topay = $days * $salary;
    }

    return $topay;
}

<强> 的index.php

检查index.php

中的拼写错误
include_once("php_includes/function.php");