开发者

PHP pass variable to foreach loop from a mySQL result

I need to pass a开发者_开发知识库 variable to a foreach loop from a mySQL result.

So I have this code:

    $GetClaim = "SELECT * FROM cR_Claimants WHERE memberID = '".$memberID."' AND ParentSubmission ='".$refNumb."'";
    $resultGetClaim=mysql_query($GetClaim) or die("Error select claimants: ".mysql_error());
    while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
    $name = $rowGetClaim['Name'];
$city = $rowGetClaim['city'];
$region = $rowGetClaim['region'];

    }

Now I need to pass the variable to the foreach

    foreach($name as $k=>$v) {
    echo $city;
echo $region;
etc..
    }

The above code does not work. I think I cannot pass a variable from a mySQL loop. The problem is also tat every row I get from the database should be related to the specific $name. So obvioiusly one $name will have its own $city etc..

How do I achieve this?

Please help


You are not retrieving an array with all returned records, you are retrieving an array which contains a single record.

To get the next name (the next record), you must make another call to mysql_fetch_array.

The code you present does that implicitly by assigning $rowGetClaim within a while conditional. A failed mysql_fetch_array call would return false, which would exit the while loop.

There is absolutely no need to use the for each as you presented. Just place the echo right after the assignment (e.g.

$region = $rowGetClaim['region'];

echo $region


Either out put directly fromt eh loop or build an array and then loop through it.

while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
  echo $rowGetClaim['Name'];
  echo $rowGetClaim['city'];
  echo $rowGetClaim['region'];

}

OR

while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
  foreach($rowGetClaim as $k => $v{
    echo $v;
  }
}

OR

$names = array();
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
  $names[] = $rowGetClaim;
}


foreach($names as $data){
  foreach($data as $k => $v) {
    echo $v;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜