1

I'm trying to add data from database to 2-dimensional array and then unpacking.

This function is in a folder named imsConnection.php

function getCurrency() {
  global $cn;
  $sql = "select * from Currency";
  $res = mysqli_query($cn, $sql);
  $a = array();
  if (mysqli_num_rows($res) > 0) {
    while ($row = mysqli_fetch_array($res)) {
      $a[] = array($row['currencyID'], $row['currencyName']);
    }
  }
  return $a;
}

And to unpack it into drop box:

<select name="drpCurrency" required>
  <?php
    require_once("imsConnection.php");
    $a = getCurrency();
    foreach($a as $i) {
      echo "<option value='$i'>$a[$i]</option>";
    }
  ?>
</select>
1
  • 3
    You don't need $a[$i] as $i is already the element - just echo the $i['currencyName'] Commented Mar 17, 2019 at 10:53

1 Answer 1

2

To make a formal answer: If you create multi dimentaion array and you loop with foreach you need to echo the value according the key you need. In you case:

    foreach($a as $i)
        echo "<option value='" . $i["currencyID"] ."'>" . $i['currencyName'] . "</option>";

I recommend you change your array do be according key - change the getCurrency function as:

while($row = mysqli_fetch_array($res)){
    $a[$row['currencyID']] = $row['currencyName'];

Then you can use it as:

$a = getCurrency();
foreach($a as $k => $i)
    echo "<option value='$k'>$i/option>";

Assuming you want the value as currency ID and the option content as the currency name

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.