如何从另一个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>"; 

    }
 ?>
评论
顽固不化
顽固不化

Because $data is declared inside the function, it exists in the functions scope only. To get the value of $data in your code, you will need to assign the result of the function a variable like so (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>"; 

    }
 ?>

点赞
评论