dsc862009 2010-10-15 06:13
浏览 66
已采纳

(PHP)MySQL选择带有$ _GET数组的查询

What I'm trying to do is go from a search URL such as this:

search.php?president=Roosevelt,+F.&congress=&nomination_received_by_senate=&state=CT

To a MySQL query like this:

SELECT `name` FROM `nominations` WHERE president=`Roosevelt, F.` AND state=`CT`

I have some code that strips any empty values from the URL, so I have an array as such:

Array ( [president] => Roosevelt, F. [state] => CT )

Going from this to the SQL query is what is giving me trouble. I was hoping there might be some simple means (either by some variation of PHP's join() or http_build_query()) to build the query, but nothing seems to work how it needs to and I'm pretty lost for ideas even after searching.

Not sure if it would require some messy loops, if there is a simple means, or if the way I'm going about trying to accomplish my goal is wrong, but I was hoping someone might be able to help out. Thanks in advance!

Edit: To clarify, sometimes the inputs could be empty (as in the case here, congress and nomination_received_by_senate), and I'm hoping to accommodate this in the solution. And yes, I intend to implement means to avoid SQL injection. I have only laid out the basics of my plan hoping for some insight on my methods.

  • 写回答

2条回答 默认 最新

  • dongle19863 2010-10-15 06:23
    关注

    You could build up your query string like this if your GET params match your db fields:

    $field_array = array('president', 'congress', 'nomination_received_by_senate', 'state');
    $query = 'SELECT `name` FROM `nominations` WHERE ';
    $conditions = array();
    foreach($field_array as $field) {
       $value = $_GET[$field];
       if(empty($value)) continue;
       $condition = mysql_real_escape_string($field) . '` = ';
       $quote = '';
       if(!is_numeric($value)) $quote = '"';
       $condition .= $quote . mysql_real_escape_string($value) . $quote;
       $conditions[] = $condition; 
    }
    
    $query .= implode(' AND ', $conditions) . ';';
    
    //perform query here...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程