0

I have a MySQL Query with following code:

$stmt_offer = $pdo->query("SELECT * FROM `offers` WHERE `fs` = '1' ORDER BY `id` DESC LIMIT 15");


  foreach ($stmt_offer as $row):
    $array_s['hbid']        = $row['ang_id'];
    $array_s['title']       = $row['titel'];
    $array_s['size']        = $row['qm'];
    $array_s['description'] = $row['beschreibung'];
  endforeach;

  $array_object['response'] = $array_s;
  $array_offer['offer']     = $array_object;

  echo json_encode($array_offer);

The Code works finde, but i get only one result back.

My Output:

{
 "offer":
  {
   "response":
    {
     "hbid":"1234567",
     "title":"Test",
     "size":"100",
     "description":"my_description"
  }
 }
}

What's the error in the foreach code?

2

1 Answer 1

2

You're overwriting $array_s everytime you loop.

Try this instead

$stmt_offer = $pdo->query("SELECT * FROM `offers` WHERE `fs` = '1' ORDER BY `id` DESC LIMIT 15");


 $i = 0;
 foreach ($stmt_offer as $row):
   $array_s[$i]['hbid']        = $row['ang_id'];
   $array_s[$i]['title']       = $row['titel'];
   $array_s[$i]['size']        = $row['qm'];
   $array_s[$i]['description'] = $row['beschreibung'];
   $i++;
 endforeach;

 $array_object['response'] = $array_s;
 $array_offer['offer']     = $array_object;

 echo json_encode($array_offer);

What Iam doing here is: I've set a $i counter, so everytime you'll loop passing the values to the array, I'm specifying what position it will be. Before, you were overwriting the array everytime you loop, so the result would aways be the last item your query has fetched.

Sign up to request clarification or add additional context in comments.

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.