2011-04-16 212 views
1

我正在使用PHP在我的数据库上执行MySQL SELECT,并且我想遍历结果。我正在使用mysql_fetch_array()来做到这一点。我最初使用while循环来循环遍历结果,我遇到的问题是,在循环中,我需要获取当前循环的行。我认为for循环会这样做,因为那样我就会有$ i问题的价值在于我认为它不会起作用。以下是我的代码。是否有可能做我正在问的事,我是否正确地做了这件事?如何使用for循环遍历mysql_fetch_array()?

$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)); 

} 

回答

5

使用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

我会使用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]; 
}