0

I have the following PHP code.

$stmt = $pdo->prepare("SELECT * FROM memberships WHERE mb_status = 'enabled'");
$stmt-> execute();

$mbData = array();
while($f = $stmt->fetch()){
  $mbData[] = $f;
  $mbsId = $f['mb_id'];

  $stmtUpg = $pdo->prepare("SELECT * FROM upgrade_validities WHERE upval_membership = :mbs");
  $stmtUpg-> bindValue(':mbs', $mbsId);
  $stmtUpg-> execute();

  $upgVal = array();
  while($uf = $stmtUpg->fetch()){
    $upgVal[] = $uf;
  }
}
$smarty->assign('mbData', $mbData);
$smarty->assign('upgVal', $upgVal);

Smarty code using foreach

{foreach from=$mbData key=k item=b}
  {$b.mb_name}
  <!-- Listing Item -->
  {foreach from=$upgVal key=k item=a}
      <h3>Member Id: {$a.upval_id}</h3> // doesn't get displayed
  {/foreach}
  <!-- Listing Item / End -->
{/foreach}

Here, the Member Id in the nested foreach loop isn't getting displayed. I don't know what is the error I am making.

4
  • Instead of using '{$a.upval_id}' try using '{$a["upval_id"]}'. Commented Dec 5, 2020 at 19:54
  • @CharlesEF before you recommend me that, are you familier enough with smarty? Plus, it didn't work. Also, please note that if the nested bit of for loop would seem to work, then even if I do not get the value to {$a.upval_id}, I will still get Member Id: as text appearing for number of counts. So here, it seems maybe my while loop logic has some issues. Commented Dec 5, 2020 at 20:21
  • It's usually a better approach to run database query inside a loop. In this case you can easily run one query to get the info you need. Commented Dec 5, 2020 at 20:37
  • @RedStar Entertainment Oh, sorry I didn't realize I was looking at smarty code. I guess I confused it with PHP. Commented Dec 6, 2020 at 1:23

1 Answer 1

1

PHP:

$stmt = $pdo->prepare("SELECT * FROM memberships WHERE mb_status = 'enabled'");
$stmt-> execute();

$mbData = array();
while($f = $stmt->fetch()){
  $mbData[] = $f;
  $mbsId = $f['mb_id'];

  $stmtUpg = $pdo->prepare("SELECT * FROM upgrade_validities WHERE upval_membership = :mbs");
  $stmtUpg-> bindValue(':mbs', $mbsId);
  $stmtUpg-> execute();

  // change begin
  $upgValTemp = array();
  while($uf = $stmtUpg->fetch()){
    $upgValTemp[] = $uf;
  }
  $upgVal[$mbsId] = $upgValTemp;

}
$smarty->assign('mbData', $mbData);
$smarty->assign('upgVal', $upgVal);

SMARTY:

{foreach from=$mbData key=k item=b}
  {$b.mb_name}
  <!-- Listing Item -->
  {foreach from=$upgVal[$b.mb_id] key=k item=a} {* changed here *}
      <h3>Member Id: {$a.upval_id}</h3>
  {/foreach}
  <!-- Listing Item / End -->
{/foreach}
Sign up to request clarification or add additional context in comments.

1 Comment

you welcome :) would me nice if you mark as accepted answer :)

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.