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