0
$aRow = array();
$query = "SELECT id, name FROM myTable";
while ($row = mysqli_fetch_assoc($db, $query)) {
    $aRow[] = $row;
}

Now that I have several records in $aRow[], I'd like to iterate the $aRow[id] like this:

foreach ($aRow as $thisRow) {
    $anID = $thisRow[id];
    $query = "SELECT amount FROM mySubTable WHERE myTableID = {$anID}";
    .
    .
    .
}

That doesn't seem to work - $anID doesn't have the expected value. How do I address the associative PHP array?


ETA: To more finely filter my question, after the WHILE completes, I have an array of DB records in $aRow[] that correspond to the database. Maybe I have: $aRow[1, 'Sally'], $aRow[2, 'Dick'], and $aRow[3, 'Jane'].

How to I assign a new variable to 'Dick'? $myVar = $aRow[?] such that $myVar will equal 'Dick'?

Dan A
  • 103
  • 2
  • 10
  • 1) You probably want to execute the query first before you fetch the results 2) `mysql_fetch_assoc` only takes 1 argument. 3) You need quotes if you want to access your array index, otherwise it will be seen as a constant – Rizier123 Mar 22 '16 at 15:53
  • 2
    [**Please, don't use `mysql_*` functions in new code**](http://stackoverflow.com/q/12859942). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). – Rizier123 Mar 22 '16 at 15:55

1 Answers1

0
 $link = new mysqli('localhost', 'myuser', 'mypass', 'dbname');

 $query1 = "SELECT id, name FROM myTable";
 $result1 = $link->query($query);   
 while ($row = result1->fetch_array(MYSQL_ASSOC)) 
 {
   $query2 = "SELECT amount FROM mySubTable WHERE myTableID = $row[id]";
   $result2 = $link->query($query); 
   .
   .
   .
 }

May be the above code is what you are looking for

Sachin
  • 2,627
  • 1
  • 19
  • 35