1
我有下面的PHP代碼。它應該從數據庫中選擇多達10行,並將這些信息輸入到上面定義的數組中,以便稍後在代碼中打印並打印在頁面上。有三行應該選擇,但它只是選擇最新的一行。任何想法爲什麼?此代碼是否循環遍歷MySQL返回的多行?
//create arrays for storing each tests information
$subject = array();
$tag = array();
$title = array();
$creator = array();
$creation_date = array();
$test_type = array();
$test_id = 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
{
$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]'"; //selects tags for test
$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 tag_ids were gathered from the database
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$thisTag = $row['tag_id'];
$q = "SELECT name FROM tags WHERE tag_id='$thisTag' LIMIT 1"; //selects tag name
$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 tags were gathered from the database
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$tag[$i][] = $row['name'];
}
}
}
}
$i++;
}
}//end of SELECT if
適當地縮進你的代碼或半身像。 – coreyward 2011-04-16 23:56:36
修正了它,等待同行評審 – Ben 2011-04-17 00:05:33
您確定要選擇3行嗎?如果你在phpMyAdmin上運行相同的查詢(例如)它是否返回你想要返回的內容?我只是問,因爲經常看到別人在其他地方尋找問題的人。 – Frankie 2011-04-17 00:15:16