dowm41315 2017-03-10 13:55
浏览 45
已采纳

在PHP中从列表框构建查询

I have a page where I am wanting to allow a user to select fields from a select that exist in a table, then display the contents of those fields on screen. I have set-up the select like so

<select name="queryfields" size="12" multiple="multiple" tabindex="1">
<option value="firstname">firstname</option>
<option value="lastname">lastname</option>
<option value="address">address</option>
<option value="phone">phone</option>

And I know to discover what options were selected I can use this:

<?php
    header("Content-Type: text/plain");

    foreach ($_GET['queryfields'] as $selectedOption)
        echo $selectedOption."
";
?>

And that gives me an array of the fields selected. However, how do I then parse the array to generate my full query? For example, let's say that firstname, lastname were selected. I would then want to build my query like this:

Select firstname, lastname from employeedata

Unknown to me, is how to get the data from the array into a select statent like my above code snippet.

  • 写回答

2条回答 默认 最新

  • douya2982 2017-03-10 14:21
    关注

    Try This:

    $sql = '';
    $selected_fields = array();   
    foreach ($_GET['queryfields'] as $selectedOption){
        //echo $selectedOption."
    ";
        $selected_fields[] = $selectedOption;
    }
    if(!empty($selected_fields)){
        $fields = implode(',', $selected_fields);
        $sql = 'SELECT '.$fields.' from employeedata'; 
    }
    

    //print query if it is not empty

    if(!empty($sql)){
        echo $sql;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符