moosavi moosavi - 6 months ago 18
PHP Question

how to retrieve an array from php function?

i get list of students from database in array and return it with function:

class StudentClass
{
public function getAllStudent()
{
$host = "localhost";
$database = "mms_db";
$username = "root";
$password = "";
$dns = "mysql:host=$host; dbname=$database";
$connect = new PDO($dns, $username, $password);
$connect->query("set names utf8");
$connect->query("set charset utf8");
$sql = "select * from students";
$result = $connect->prepare($sql);
$result->execute();
$starraye = $result->fetchAll();
return $starraye;
}
}


now i want to retrieve this array and echo with foreach():

<?php
include ("StudentClass.php");
$student_object = new StudentClass();
$student_object->getAllStudent();
foreach ($starraye as $rows)
{
echo $rows['fname'];
}


but i get error:



tanks!

Answer

You need to store the return array, After a function call you have to store the return data in any variable. You did't make it so the error shows up.

include ("StudentClass.php");
$student_object = new StudentClass();
$starraye = $student_object->getAllStudent(); //store here
foreach ($starraye as $rows)
{
    echo $rows['fname'];
}