php - 变量在函数内未定义,无法在函数内到达 MySQL $connection

标签 php mysql function mysqli fetchall

当我在页面上使用它时,我有一个代码可以工作,但我试图使它成为一个函数。我无法让它工作,似乎变量 $customer 和 $system 没有被发送到代码。即使我在 Raw 中输入它。知道有什么问题吗? $Customer 是客户的名字,$system 可以是 'Source' 或 'Target'。

function status_total($customer, $system){
        $sql_customer       = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
        $customer_selection = mysqli_query($conn,$sql_customer);
        $customer_row       = mysqli_fetch_assoc($customer_selection);
        $env_lines          = $customer_row["Env_Lines"];
        $cust_id            = $customer_row["Cust_ID"];
        $sql_last_records   = "SELECT * FROM $system WHERE Cust_ID = $cust_id ORDER BY Time DESC LIMIT $env_lines";
        $record_selection   = mysqli_query($conn, $sql_last_records);               

        $result = mysqli_fetch_all($record_selection, MYSQLI_ASSOC);
        $states = array_column($result, "Stat");

        if($states == array_fill(0, count($states), "Run")) {
            echo "Success";
        } else 
            echo "Fail";

    }

https://gist.github.com/R2D2-05/78d81566e4bf0eafd1fa

最佳答案

您的代码的问题是 $conn 变量,该变量在函数内被视为局部变量。你应该:

function status_total($customer, $system){
        global $conn;

        $sql_customer       = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
        $customer_selection = mysqli_query($conn,$sql_customer);
        $customer_row       = mysqli_fetch_assoc($customer_selection);
        $env_lines          = $customer_row["Env_Lines"];
        $cust_id            = $customer_row["Cust_ID"];
        $sql_last_records   = "SELECT * FROM $system WHERE Cust_ID = $cust_id ORDER BY Time DESC LIMIT $env_lines";
        $record_selection   = mysqli_query($conn, $sql_last_records);               

        $result = mysqli_fetch_all($record_selection, MYSQLI_ASSOC);
        $states = array_column($result, "Stat");

        if($states == array_fill(0, count($states), "Run")) {
            echo "Success";
        } else 
            echo "Fail";

    }

或者您也可以通过函数传递$conn,因此将函数的定义更改为:

function status_total($conn, $customer, $system){...}

关于php - 变量在函数内未定义,无法在函数内到达 MySQL $connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404270/

相关文章:

javascript - Mysql命令中的时间延迟

php - 如何读取 PHP 和 HTML 中的查询字符串?

java - 如何对 java.sql.Time 对象进行算术运算?

java - 类未找到异常 : Didn't find class "java.sql.SQLType" on path: DexPathList

sql - 我可以在 SQL Server 上创建动态表值函数吗?

php - 通过查询拆分列以将提取内容插入到另一列中。不工作

php - 显示 MySQL 数据库中多个复选框的值

mysql - 将 MYSQL 转储附加到表

php - 如何在 javascript/jQuery 中调用文本函数?

r - 创建一个函数来替换计算 session 的列中的 NA