簡體   English   中英

php mysqli循環太多結果

[英]php mysqli looping too many results

我在遍歷數據庫檢索結果時遇到了一個小問題,我理解為什么會遇到這個問題,但是由於我的PHP並不是最好的,所以不太確定如何實現該解決方案。 我瀏覽了論壇,但找不到任何解決我的問題的方法。

從下面看,當我只想要6個結果,每個項目2個項目時,我的輸出將給我12個結果:對於每個循環,數組中計數12個項目是有意義的,因此它將輸出12次,給我每個項目的重復項。 我如何最好地處理這個問題。

    MyTable1:                          myTable2:
    |   ID   |  Name  |           | NameID   |       Details     |   
    |--------|--------|           |----------|-------------------|
    |   0    | bob    |           |   0      | lives in the city |
    |   1    | david  |           |   1      | lives in a caravan|
    -------------------           --------------------------------

我的MSQLI查詢:

     $qryRandom   =  "SELECT  MyTable1.ID,  MyTable2.Details
                      FROM  MyTable1
                      INNER JOIN  MyTable2
                      ON MyTable1.ID=MyTable2.NameID 
                      ORDER BY RAND()
                      LIMIT 6;";

我的PHP(一般示例)。

    $resultR= $con->query($qryRandom) or die($mysqli->error.__LINE__);
    while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
    {
    foreach ( $row as $key=>$value ){ // loops 12 times here as there is 6 items x 2 values
    echo $key.": ".$value."<br>";

    }

 }

結果輸出:

    bob lives in city
    bob lives in city
    David lives in caravan
    David lives in caravan
    john lives in the car 
    john lives in the car  // doubles of each entry is my issue
   // hope I was thorough and provided enough info for my scenario. 

我想出的解決方案對我仍然不滿意。

   while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
   {
    for ($i = 0; $i<1;$i++){
    echo $row['name'].$row['details']."<br>";
    }
    }

因此,我更確定有解決此問題的更好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM