doufunuo4787 2017-08-12 19:08
浏览 29
已采纳

在数据库中查找匹配的行,其中列与动态数组中的一个条目匹配

I have a table with multiple columns in it, one of which, labeled 'ID', contains a unique number. I am sending a list of values to pull to a server-side php script that uses a prepared statement to make the pull. Through some research I found that I believe I am looking for IN inside of my statement. I get how to hardcode a list in to the statement, such as: SELECT * FROM spotzz WHERE ID IN (465, 732, 219) or something along those lines, but my confusion comes from the prepared statement. I need a ? for every value I'm passing to the statement, but if the length of the list is not always the same, how do I do this?

  • 写回答

1条回答 默认 最新

  • douyonglang4845 2017-08-12 19:16
    关注

    You can dynamically generate the prepared statement string based on how many values are in your array:

    $values = [1,2,3,4];
    
    $sql = "SELECT * FROM spotzz WHERE `ID` IN (" .
        // array_fill() creates an array with as many '?' as there are
        // elements in $values. implodes() glues the new array elems with a ","
        implode(',', array_fill(0,count($values),'?')) .
        ")";
    
    echo $sql; // SELECT * FROM spotzz WHERE `ID` IN (?,?,?,?)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站