doumeng3188 2015-03-31 09:26
浏览 95
已采纳

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

I have three .php files.

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;
}

And I have the index.php file to call the files and use them.

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

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

The problem is that it will not connect to the database and it returns some errors:

Notice: Undefined variable: db_conx in D:\xampp\htdocs\manager\pages\php_includes\functions.php on line 5

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in D:\xampp\htdocs\manager\pages\php_includes\functions.php on line 5

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in D:\xampp\htdocs\manager\pages\php_includes\functions.php on line 11

And then it prints the value (since it does not currently use database any values). What I tried: I tried to put the functions.php content directly into the index.php file, I tried to call the db_conx.php file inside the functions.php file.

  • 写回答

1条回答 默认 最新

  • douren0558 2015-03-31 09:30
    关注

    You need to define the value the in function.php.checkout the below code

    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

    Check the typo mistake in index.php

    include_once("php_includes/function.php");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器