chr*_*ude 1 php mysql loops for-loop
我正在SELECT使用PHP在我的数据库上执行MySQL ,我想循环遍历结果.我正在使用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));
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)