2016-01-22 17 views
1

我試圖選擇與環路的ID:的mysql-如何選擇與環路

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "db"; 
// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Check connection 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 
$str= '8,2,3,4,5,6,7'; 
$strr=explode(',' , $str); 
$i=0; 
while($i<count($strr)){ 
    $sql = "select id,name from `live_table` where `id`='$strr[$i]' "; 
    $result = mysqli_query($conn, $sql); 
    $i++; 

    if (mysqli_num_rows($result) > 0) { 
    // output data of each row 
     while($row = mysqli_fetch_array($result)) { 
      $result_array[] = $row; 
     } 
     foreach ($result_array as $rows) { 
      // The output 
     echo '<tr>';   
     echo '<td class="small">'.$rows['id'].'</td>'; 
     echo '<td class="small">'.$rows['name'].'</td>'; 
     echo '</tr>'; 
    } 
} 
} 
?> 

輸出:

8,貝爾,8,貝爾,2,悉尼,8,貝爾2,悉尼,3,切爾西,8,貝爾,2,悉尼,3,切爾西,如圖4所示,艾力,8,貝爾,2,悉尼,3,切爾西,如圖4所示,艾力,5,布蘭登·,8,貝爾,2 ,悉尼,3,切爾西,4,亞歷克,5,布倫登,6,納丁,8,貝爾,2,悉尼,3,切爾西,4,亞歷克,5,布倫登,6,納丁,7,普雷斯科特,

我在做什麼錯了?

+5

什麼是你想要的輸出? –

+1

你有一個反作用,在'
錯字或是在你的代碼? – BRoebie

+0

我想輸出:
'id:8,2,3,4,5,6,7'
不要重複 –

回答

1

在每次迭代執行while循環之前,您需要初始化$result_array

修改代碼塊:

if (mysqli_num_rows($result) > 0) { 

    $result_array = array(); // ADD THIS LINE 

    while($row = mysqli_fetch_array($result)) { 
     $result_array[] = $row; 
    } 
    foreach ($result_array as $rows) { 
     // The output 
     echo '<tr>';   
     echo '<td class="small">'.$rows['id'].'</td>'; 
     echo '<td class="small">'.$rows['name'].'</td>'; 
     echo '</tr>'; 
    } 
} 

您還可以優化該代碼使用while循環中的HTML塊:

if (mysqli_num_rows($result) > 0) { 
     // output data of each row 
     while($row = mysqli_fetch_array($result)) { 
      echo '<tr>';   
      echo '<td class="small">'.$row['id'].'</td>'; 
      echo '<td class="small">'.$row['name'].'</td>'; 
      echo '</tr>'; 
     }   
}