如何使用for循环遍历mysql_fetch_array()?

时间:2011-04-16 22:20:00

标签: php mysql loops for-loop

我正在使用PHP在我的数据库上执行MySQL SELECT,我想循环遍历结果。我正在使用mysql_fetch_array()来执行此操作。我最初使用while循环来遍历结果我遇到的问题是在循环中我需要得到循环当前所在的行。我认为for循环会这样做因为那样我会有$ i得到问题的价值是我不认为它会起作用。以下是我的代码。是否有可能做我要问的事情,我是以正确的方式做的吗?

$q = "SELECT test_id, title, subject, type, creation_date FROM tests WHERE user_id='$user_id' LIMIT 10"; //select first ten of users tests
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

if (mysqli_affected_rows($dbc) > 0) {//if the query ran correctly and the test details were gathered from the database

$row = mysqli_fetch_array($r, MYSQLI_ASSOC)

for($i=1; i<10; i++) {

$test_id = $row['test_id'];
$test_type = $row['type'];
$creation_date = $row['creation_date'];
$creator = $user_id;
$title = $row['title'];
$subject = $row['subject'];

$q = "SELECT tag_id FROM test_tags WHERE test_id='$test_id[$i]"; //select tags corresponding to this test
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

}

2 个答案:

答案 0 :(得分:6)

像以前一样使用while循环,只保留一个变量$i,每次迭代增加一次。

$q = "SELECT test_id, title, subject, type, creation_date FROM tests WHERE user_id='$user_id' LIMIT 10"; //select first ten of users tests
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

if (mysqli_affected_rows($dbc) > 0) {//if the query ran correctly and the test details were gathered from the database

    $row = mysqli_fetch_array($r, MYSQLI_ASSOC)
    $i = 0;

    while ( $row = mysqli_fetch_array($r, MYSQLI_ASSOC) ) {
        $test_id = $row['test_id'];
        $test_type = $row['type'];
        $creation_date = $row['creation_date'];
        $creator = $user_id;
        $title = $row['title'];
        $subject = $row['subject'];

        $q = "SELECT tag_id FROM test_tags WHERE test_id='$test_id[$i]"; //select tags corresponding to this test
        $r2 = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

        $i += 1;
    }
}

答案 1 :(得分:1)

我会使用foreach()构造来遍历结果对象。像这样:

//select first ten of users tests
$q = "SELECT test_id, title, subject, type, creation_date FROM tests WHERE user_id='$user_id' LIMIT 10"; 
$r = mysqli_query($dbc, $q);
$i = 0;
//loop through result object:
foreach ($r as $row) {
  $row[$i]['test_id'] = $test_id;
  //...

  $q = "SELECT tag_id FROM test_tags WHERE test_id='$test_id[$i]"; //select tags corresponding to this test
  $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

  //loop through the new result:

  foreach ($r as $tag) {
    $tags[] = $tag;
  }

  $i++; //increment counter.

  //Not sure where you're going from here, but...

  $row[$i]['tags'] = $tag; //add tags array to $row
  return $row[$i];
}