0

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!

2
  • 1
    you need to store the returned array. Commented May 25, 2016 at 9:45
  • 1
    you need to store the return value $starraye = $student_object->getAllStudent(); Commented May 25, 2016 at 9:45

2 Answers 2

2

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

1

Function getAllStudent is returning data as array so you have to store the return array in some variable and you can use that variable...

So Use it like

$output_array = $student_object->getAllStudent();
if($output_array!= false)
{
    foreach ($output_array as $rows)
    {
        echo $rows['fname'];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.