循环遍历具有非顺序索引

时间:2021-02-18 10:05:07

标签: php mysql

我有一个像这样的 MySQL 表

<头>
索引(自动递增) 数据 类型
1 a1 1
3 a2 1
4 b62 3
9 m52 1

我用这段代码循环遍历它

for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}

但是正如你所看到的,它会失败,因为自动递增的索引不是顺序的。所以在 i=2 时它会失败,而不会使其达到 i=3。

知道如何让它选择表中的下一个索引

1 个答案:

答案 0 :(得分:0)

简单的解决方案

  • 不要使用 * 使用指定的列名

  • 使用一个查询来检索整个结果集

  • 使用 OOP 方法并避免重复代码(您不需要更改连接,但您可以:

     // From...
     $db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
    
     // To...
     $db = new mysqli($db_host,$db_user,$db_pass,$db_name)
    
  • 我假设 type 是一个整数字段;无需在查询中使用引号

代码

// Run the query to select the messages
$sql   = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query =  $db->query($sql);

// Option 1
//     Loop though result set with a foreach loop
foreach ($query as $message) {
    echo $message[0];
}

// Option 2
//     Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
    echo $message["data"];
}