如何从存储在另一个 php 文件中的函数中 return 变量?
How to return variable from a function stored in another php file?
我想做的是,在 crud.php 文件中创建一个函数,该函数将从数据库中获取数据。之后,我试图在 index.php 文件中调用该函数。
我收到此错误:
**注意:未定义变量:数据在C:\xampp\htdocs\shop\index.php第11行
警告:为 C:\xampp\htdocs\shop\index.php 中的 foreach() 提供的参数无效,第 11 行**
crud.php 文件:
<?php
function getResults($sql){
$server = "localhost";
$user = "root";
$pass = "";
$db = "cms";
$conn = mysqli_connect($server, $user, $pass, $db);
if (!$conn) {
die("connection Failed:".mysqli_connect_error());
}
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
while ($row = mysqli_fetch_assoc($result)) {
$data = $row;
}
}
return $data;
}
?>
index.php 文件:
<?php
include_once ('inc/crud.php');
$sql = "SELECT * from blog";
getResults($sql);
foreach ($data as $x => $xvalue) {
echo "Key: ". $x."<br>";
echo "Value: ". $xvalue."<br>";
}
?>
因为$data
是在函数内部声明的,所以它只存在于函数scope中。要在您的代码中获取 $data
的值,您需要将函数的结果分配给一个变量,如下所示 (index.php):
<?php
include_once ('inc/crud.php');
$sql = "SELECT * from blog";
$data = getResults($sql);
foreach ($data as $x => $xvalue) {
echo "Key: ". $x."<br>";
echo "Value: ". $xvalue."<br>";
}
?>
我想做的是,在 crud.php 文件中创建一个函数,该函数将从数据库中获取数据。之后,我试图在 index.php 文件中调用该函数。
我收到此错误:
**注意:未定义变量:数据在C:\xampp\htdocs\shop\index.php第11行
警告:为 C:\xampp\htdocs\shop\index.php 中的 foreach() 提供的参数无效,第 11 行**
crud.php 文件:
<?php
function getResults($sql){
$server = "localhost";
$user = "root";
$pass = "";
$db = "cms";
$conn = mysqli_connect($server, $user, $pass, $db);
if (!$conn) {
die("connection Failed:".mysqli_connect_error());
}
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result)>0) {
while ($row = mysqli_fetch_assoc($result)) {
$data = $row;
}
}
return $data;
}
?>
index.php 文件:
<?php
include_once ('inc/crud.php');
$sql = "SELECT * from blog";
getResults($sql);
foreach ($data as $x => $xvalue) {
echo "Key: ". $x."<br>";
echo "Value: ". $xvalue."<br>";
}
?>
因为$data
是在函数内部声明的,所以它只存在于函数scope中。要在您的代码中获取 $data
的值,您需要将函数的结果分配给一个变量,如下所示 (index.php):
<?php
include_once ('inc/crud.php');
$sql = "SELECT * from blog";
$data = getResults($sql);
foreach ($data as $x => $xvalue) {
echo "Key: ". $x."<br>";
echo "Value: ". $xvalue."<br>";
}
?>