dongyan7950 2016-09-24 05:06
浏览 28
已采纳

通过更改为单个查询而不是将其放入循环来进行优化

I have a table in data base. It contains 3 columns: ID, name, type. I have an array in my PHP script with some of those IDs (not in any order, maybe duplicates). I want to echo out those items from the table, that I have IDs in the array. I tried doing this with a for loop:

$items = array(1, 8, 5, 3, 2, 1,  5, 5);
for ($i=0; $i < count($items); $i++) {
    $query = mysqli_query($connect, "SELECT * FROM weapons WHERE id='$items[$i]'");
    $row = $query->fetch_assoc();

    echo $row['name'] . ', ' . $row['type'];
}

I think its not good practice to use call query in a loop, because if the loop gets too big, it may slow that the process. What can I achieve the same result, without putting query in a loop?

  • 写回答

2条回答 默认 最新

  • drzyeetvt41077335 2016-09-24 05:14
    关注

    Use IN keyword for this

    $query = mysqli_query($connect, "SELECT * FROM weapons WHERE id IN (1, 8, 5, 3, 2,5) ");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击