php - 如何从存储在另一个 php 文件中的函数返回变量?
问题描述
我想要做的是,在 crud.php 文件中创建一个函数,该函数将从数据库中获取数据。之后,我试图在 index.php 文件中调用该函数。
我收到此错误:
**注意:未定义变量:第 11 行 C:\xampp\htdocs\shop\index.php 中的数据
警告:为第 11 行 C:\xampp\htdocs\shop\index.php 中的 foreach() 提供的参数无效**
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
是在函数内部声明的,所以它只存在于函数作用域中。要在代码中获取 的值$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>";
}
?>
推荐阅读
- java - 无法获取用于配置数据库 Tomcat 的 .properties 文件
- android - 更新 Android Studio 后的代理问题
- android - 如何在 Android Room SQL 中使用对象属性?
- typescript - 使用模板 Vuetify 表单
- javascript - 从多个子组件更新父组件状态而不考虑更新的状态值
- c# - 使用来自 dll 的参数获取 nunit (2.5.10) TestCases
- python - Python 2 根据阈值删除最旧的目录
- perl - Perl 意外行为:croak 与 try catch
- python-3.x - 在python中添加唯一值以重复列表值
- docker - Docker-compose 文件两次构建相同的图像