douhe6255 2016-02-14 16:39
浏览 14
已采纳

如何在PHP中进行下拉基础MySQL查询

I have 6 <select> boxes. I am making a report base on <select> boxes. What I have done is make a form and and set method to GET and then getting these values through $_GET method on next page. Like

<form method="get" action="report.php">

<select name="select1">
<option value="none">Select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>


<select name="select2">
<option value="none">Select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select name="select3">
<option value="none">Select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
.....................
</form>

Here is PHP code. (These are all sample data :P) Just trying to tell you people my problem. I am getting all values an check if it's value equal to none or not and do this, etc.

if(
$cby == "none" 
&& $crequirment == "none" 
&& $cdepartment == "none" 
&& $period == "none" 
&& $ccontact == "none" 
&& $cattend == "none"
)
{
    $query = mysqli_query($db, "SELECT * FROM customer");
}



else if (
$cby != "none" 
&& $crequirment == "none" 
&& $cdepartment == "none" 
&& $period == "none" 
&& $ccontact == "none" 
&& $cattend == "none"
)
{
    $query = mysqli_query($db, "SELECT * FROM customer WHERE cby = $cby");
}
else if (
$cby == "none" 
&& $crequirment == "none" 
&& $cdepartment != "none" 
&& $period == "none" 
&& $ccontact == "none" 
&& $cattend == "none")
{
    $query = mysqli_query($db, "SELECT * FROM customer WHERE cdepartment = $cdepartment");
}
else if..........

What I want is to make as simple as possible. What method should I have to adopt for it?

  • 写回答

1条回答 默认 最新

  • doxd96148 2016-02-21 09:08
    关注

    Optimize your code.

    Create selects with names like data[cby], data[crequirment].
    Instead of none use empty string.

    In PHP:

    if (isset($_GET['data']) {
        $where = [];
    
        foreach ($_GET['data'] as $name => $value) {
            if ($value != '') {
                $where[] = $name."=".$value; // sanitize `$name` and `$value` first
            }
        }
    
        if (!empty($where)) {
            $whereString = ' WHERE '.implode(' AND ', $where);
        } else {
            $whereString = '';
        }
    
        $query = mysqli_query($db, "SELECT * FROM customer".$whereString);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?