2011-04-16 209 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]; 
}