duanfu4446 2016-09-16 15:47
浏览 39
已采纳

返回php和sql中变量数组中的列所在的行

I am writing a query that will return records when the value of one of the columns matches any of the elements of an array. If I use a static array it works (see sample):

sql = "SELECT *
        FROM tasks
            WHERE
            tasks.type IN ('homework', 'chores', 'laundry')";

What if I have an array of tasks that is populated from user input that I want to use from comparison? Like this:

$task_list = //declaration and populate the array. I know it works, so I'm skipping it

sql = "SELECT *
            FROM tasks
                WHERE
                tasks.type IN "+$task_list+" ";

This gives me an error. I really am not any good at mixing php with sql and did search for the answer ... maybe I wasn't able to search properly for the right syntax.

For those that want to know, var_dump($task_list); prints the following:

array(3) { [0]=> string(8) "homework" [1]=> string(6) "chores" [2]=> string(7) "laundry" } 
  • 写回答

1条回答 默认 最新

  • douchun2158 2016-09-16 15:56
    关注

    It fails because $task_list is an array, you should do something like this :

    $task_list_str = sprintf('"%s"', implode('", "', $task_list));
    $sql = 'SELECT *
           FROM tasks
           WHERE
               tasks.type IN (' . $task_list_str . ')';
    

    It's a bit convoluted, but it stays as close as possible from your code.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题