0

What I am trying to do is, create a function in crud.php file which will fetch data from the database. After that, I am trying to call that function in the index.php file.

I am getting this error:

**Notice: Undefined variable: data in C:\xampp\htdocs\shop\index.php on line 11

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\shop\index.php on line 11**

crud.php file:

<?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 file:

<?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>"; 

    }
 ?>
Mayuresh
  • 70
  • 1
  • 7

1 Answers1

1

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 to 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>"; 

    }
 ?>

DannyXCII
  • 888
  • 4
  • 12