duandunzhuo3234 2014-09-22 13:14
浏览 179

PHP MySQL查询中的多个条件

I have a database with some records and columns: "type", "id" and others. I would like to select all records with any "type" that's mentioned in array $typearray but without records which id's are in $idarray. I tried to do something like:

$result = mysql_query("SELECT * FROM db 
    WHERE type IN('".implode("','",$typearray)."') 
    AND id NOT IN('".implode("','",$idarray)."') 
    ORDER BY date DESC LIMIT 10");

But it doesn't seem to work - the:

type IN('".implode("','",$typearray)."')

condition works fine but the second does not. At first I thought the issue was with column types - both arrays contains strings, "type" column is a VARCHAR(10) and id is INT, but changing it to string didn't help. What am I doing wrong?

EDIT:

If I print a query I get this:

SELECT * FROM db 
WHERE type IN('apple','tomato','potato') 
AND id NOT IN('20','1','10','15','8') 
ORDER BY date DESC LIMIT 10

The first condition works fine: it selects only apples, tomatoes and potatoes. The second condition does nothing and even if I type manually:

id NOT IN('20','1','10','15','8')

or

id NOT IN('20,1,10,15,8')

or

id NOT IN(20,1,10,15,8)

it still fails.

EDIT2:

Actually forget it. I'm an idiot. I've mixed up my variables a bit...

  • 写回答

2条回答 默认 最新

  • duanpendan8067 2014-09-22 13:19
    关注

    You should try this query, or at least do a echo $result, " ";, into mysql workbench to see what it give.

    And I'd say the default behavior to have when a query does not work: first in Mysql Workbench (or any SQL runner like Toad, Squirrel ...)

    $result = mysql_query("SELECT * FROM db 
        WHERE type IN('".implode("','",$typearray)."') 
        AND id NOT IN('".implode("','",$idarray)."') 
        ORDER BY date DESC LIMIT 10");
    

    If $typearray is empty, you are looking for type IN (''), which might never matches. If $idarray is empty, you are looking for id not in ('') which might always matches.

    And if $typearray or $idarray contains invalid character, you will get an error.

    [edit] by the way, if $typearray or $idarray may contains invalid character, you might use array_map and mysqli_escape_string:

    $result = mysql_query("SELECT * FROM db 
        WHERE type IN('".implode("','", array_map('mysql_escape_string', $typearray))."') 
        AND id NOT IN('".implode("','", array_map('mysql_escape_string', $idarray))."') 
        ORDER BY date DESC LIMIT 10");
    
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)