【问题标题】:Variable is undefined inside a function, cannot reach MySQL $connection inside a function变量在函数内未定义,无法在函数内访问 MySQL $connection
【发布时间】:2015-08-04 22:09:45
【问题描述】:

当我在页面上使用它时,我有一个可以工作的代码,但我试图让它成为一个函数。我无法让它工作,似乎 $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 和 $sql_customer 变量。应该是问题所在。我不会深入研究其他问题,例如在客户名称重复并限制返回数据的情况下,您很可能不会仅使用客户名称查询所需的结果。
  • ... 或挖掘其他明显的问题,如 SQL 注入漏洞,或与性能相关的问题,如检索表中的 every 列(使用 @ 987654323@) 当我们只需要两列时。
  • 是的,这是@smozgur 的错误之一,谢谢。我不认为我需要包含 $conn,因为我的 config.php 页面中有它包含在这个 function.php 页面中
  • 一个函数是一个独立的世界,除了注入的对象和变量之外,它不能从外部读取——除非你全局定义了变量,你应该避免这样做。

标签: php mysql function mysqli fetchall


【解决方案1】:

您的代码的问题是$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){...}

【讨论】:

  • 我不敢相信我自己没有发现语法错误,但我想这就是为什么我仍然是一个菜鸟哈哈。这解决了第一个 sql 问题。 $conn 部分解决了剩下的问题!谢谢,我认为不需要,因为在我的functions.php页面中包含了带有数据库连接的config.php页面。
  • 在 PHP 中,默认情况下,函数是作用域绑定的。在函数内部,您只能访问作为该函数的参数传递或在该函数中定义的变量。要在 $vars 之外访问,必须将它们声明为 global;
猜你喜欢
  • 2022-11-23
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多