php - 将sql查询放入php函数中

标签 php mysql

我试图将 SQL 查询放入 PHP 函数中,但在终端中收到以下错误

Fatal error: Call to a member function query() on a non-object in /Users/file.php on line 18

请参阅下面我的 PHP 代码的第 16 至 22 行:

function testFunction() {
     $sql = "SELECT * FROM testNumber WHERE test = '1'"
     $result = $conn->query($sql);
     return $result->num_rows;
}

$testVariable = $testFunction();
echo $testVariable;

最佳答案

在函数范围中无法访问$conn

您需要以某种方式访问​​ $conn 变量才能使用它。

您有两个选择,将 $conn 作为函数参数传递。

函数 myFunc($conn)

或使用global关键字。 (See reference for Variables Scope)

传递连接:

   function testFunction($conn) {
         $sql = "SELECT * FROM testNumber WHERE test = '1'"
         $result = $conn->query($sql);
         return $result->num_rows;
    }

    $conn = new mysqli(,,,);
    $testVariable = testFunction($conn);
    echo $testVariable

使用全局:

function testFunction() {
     global $conn;
     $sql = "SELECT * FROM testNumber WHERE test = '1'"
     $result = $conn->query($sql);
     return $result->num_rows;
}

$testVariable = testFunction();
echo $testVariable

关于php - 将sql查询放入php函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38434116/

相关文章:

javascript - 从目录和子目录中获取数组中的所有图像

MySQL 凭据在工作台中不起作用

mysql - spring mysql hibernate中的外键引用

mysql 两个唯一的列,如果插入到另一个列中,一个列中的值将被视为重复

mysql - 左连接减少返回的行数

javascript - 调用 PHP 变量到 html 输入

php - ubuntu 12.04 上的 Salt-Stack/Vagrant : php 5. 5

更新 svn 工作目录的 php 脚本

mysql - 为什么 sql = FALSE 总是返回 true

javascript - document.getElementById ('' ).style.display ='block' ;不在 Wordpress 中工作