Corren
Corren

Reputation: 79

Returns multiple values from a PHP function

Apologize for the repeated question. Return multiple values from database with function. I tried executing code, the function returns one value, where I want all the values of id and name.

Database: id and name has 9 rows. Is there anything I was missing in my code.

function readdata() { 
    $sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
    foreach ($sth as $s) {
       $object = new stdClass();
       $object->id = $s->id;
       $object->name = $s->name;
       return $object;    
    }              
}

$rd = readdata();
echo $rd->id;
echo $rd->name;

Upvotes: 1

Views: 819

Answers (3)

Markus Zeller
Markus Zeller

Reputation: 9090

This is more a suggestion than an answer. Why re-inventing the wheel? PDO already is capable of returning classes and also fetching all results into an array.

function readdata(PDO $db): array
{
  $sth = $db->prepare('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
  $sth->execute();
  return $sth->fetchAll(PDO::FETCH_CLASS);
}

$objects = readdata($db);

$objects is now an array. Each element contains a stdClass object with each column name as property.

foreach($objects as $object) {
   echo $object->id, PHP_EOL;
   echo $object->name, PHP_EOL;
}

Upvotes: 2

Serghei Leonenco
Serghei Leonenco

Reputation: 3507

May be something like this:

function readdata() { 
    $sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
    $out = [];
    foreach ($sth as $s) {
       $object = new stdClass();
       $object->id = $s->id;
       $object->name = $s->name;
       $out[] =  $object;    
    } 
    return $out;             
}
$rd = readdata();
//and here
foreach($rd as $obj){
   echo $obj->id;
   echo $obj->name;
}

Upvotes: 2

P2000
P2000

Reputation: 1062

Your foreach loop intends to run through all values of the array $sth, but returns only with the FIRST one.

You can just return $sth to get the whole array, or build a new array and append to it:

$ret = array();
foreach ($sth as $s) {
  ...
  $ret[] = $object;
  }

and then return $ret;

Upvotes: 0

Related Questions