doulan3966 2016-10-09 18:33
浏览 10
已采纳

如何处理三个以上的PHP GET变量从MySQL数据库中选择数据[重复]

This question already has an answer here:

I have a PHP page called get.php that has access to MySQL Database. I use one table called: MyTable

In the table I have more than on row. Every info has an id that I use to get the other info based on it:

$sql = "SELECT * FROM `MyTable` WHERE `id`='" . $_GET["var1"]'";
$result = $conn->query($sql);
.
.
.

So when I go to:

localhost/bb/t2/get.php?var1=1

I get the other info like Name of the info by fetching the rows.

BUT I want to deal with more than one variable:

localhost/bb/t2/get.php?var1=1&var2=2&var4=4&...

So I can get the info of every id and not one only.

I want to handle any number of variables and get it's data.

Thank you!

</div>
  • 写回答

2条回答 默认 最新

  • douershuang7356 2016-10-09 18:45
    关注

    First, it would be easier to use an array for specifying multiple ids in the URL:

    http://localhost/bb/t2/get.php?var[]=1&var[]=2&var[]=4&...
    

    This way, in your PHP code $_GET['var'] will be an array and will contain all values specified in the URL.

    Next, you have to make sure all array items (the ids) are numeric. There are many solutions for this, for example skipping non-numeric values:

    // make sure parameters are OK
    if (is_array($_GET['var'])) {
        // eliminate non-numeric values
        $ids = array_filter($_GET['var'], function($item) {
            return is_numeric($item);
        });
    }
    else {
        // invalid arguments; throw exception or do something else
    }
    

    Finally, you have to use WHERE IN in your query (and verify of course if there are actually some values in the $ids array before executing the SQL query):

    if (!empty($ids)) {
        $sql = "SELECT * FROM `MyTable` WHERE `id` IN (" . implode(",", $ids) . ")";
    }
    else {
        //TODO: no numeric ids specified, do something else...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能