Sahil Buddhadev
Sahil Buddhadev

Reputation: 73

PHP Function with array return type

I have created a function which gets all employee list who has the same salary. But it will return only the first row but I want all the data how can I do it ?

Function code

function getEmployee($employee, $salary) {
  $select = mysql_query("SELECT * FROM $employee where salary = '$$salary'");
  if ($select) {
      while ($row = mysql_fetch_array($select)) {
        $employeeInfo = array(
          'fname' => $row['fname'],
          'mname' => $row['buyQty'],
          'lname' => $row['lname'],
          'employeeCode' => $row['employeeCode'],
          'email' => $row['email'],
          'mobile' => $row['mobile'],
        );
      return $employeeInfo;
    }
  } else {
    echo mysql_error();
  }  
}

Function Call

$entry[] = getEmployee('abc', '10000');
echo "<pre>";
print_r(array_values($entry));
echo "</pre>";

Thank You

Upvotes: 0

Views: 79

Answers (3)

Ashu Jha
Ashu Jha

Reputation: 344

You are getting only one value (the last array in iteration) because you actually overwrites $employeeInfo with every iteration and at the loop termination $employeeInfo retains the last array only. Make this as array like $employeeInfo[] inside your getEmployee function.

Upvotes: 1

dinesh
dinesh

Reputation: 342

Please try

function getEmployee($employee, $salary) {
    $select = mysql_query("SELECT * FROM $employee where salary = '$$salary'");
    if ($select) {
      $allEmployeesInfo = array();
      while ($row = mysql_fetch_array($select)) {
        $employeeInfo = array(
        'fname' => $row['fname'],
        'mname' => $row['buyQty'],
        'lname' => $row['lname'],
        'employeeCode' => $row['employeeCode'],
        'email' => $row['email'],
        'mobile' => $row['mobile'],
      );
      array_push($allEmployeesInfo, $employeeInfo);
    }
    return $allEmployeesInfo;
  } else {
    echo mysql_error();
  }  
}

Upvotes: 1

Brijal Savaliya
Brijal Savaliya

Reputation: 1091

Try

while ($row = mysql_fetch_array($select)) {
        $employeeInfo[] = array(
          'fname' => $row['fname'],
          'mname' => $row['buyQty'],
          'lname' => $row['lname'],
          'employeeCode' => $row['employeeCode'],
          'email' => $row['email'],
          'mobile' => $row['mobile'],
        );
}
return $employeeInfo;

Upvotes: 4

Related Questions