1

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;
1

3 Answers 3

2

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

Comments

2

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

Comments

0

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;

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.