我试图将 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/