简体   繁体   中英

Parse PHP Array To Build Query String

I am trying to build a multi select on my php page where a user can select what fields to query from a database. I have the multi-select set-up and I am trying to work on the "behind-the-scenese" syntax for the query build portion, but when I hit my echo statement, it is not displaying what is selected.

What would be the proper way to build out a query string based off what is selected from the multi-select on the page? (Now granted I am omitting a valid connection string etc.)

<html>
<select name="employee_data[]" multiple style="min-width: 200px;" id="user_data">
<option value="EmployeeName">Employee Name</option>
<option value="TeamName">Team Name</option>
<option value="ManagerName">Manager Name</option>
<option value="Department">Department</option>
<option value="Recruiter">Recruiter</option>
<option value="RecruitingAgency">RecrutingAgency</option>
</select>
</html>
<?php
  $query = "Select employeename ";
  if (in_array('TeamName')) $query .= ",teamname"
  if (in_array('ManagerName')) $query .= ",ManagerName"
  if (in_array('Department')) $query .= ",Department"
  if (in_array('Recruiter')) $query .= ",Recruiter"
  if (in_array('RecruitingAgency')) $query .= ",RecruitingAgency"
  $query .= " FROM employeepersonelinfo where employeename = '$employeename'";

echo $query;
?>

Below is the working PHP code. Instead of checking each, you can use implode() .

<?php
 if (!isset($_POST['employee_data'])) die();
 $query = "Select employeename ";
 $query .= implode(', ', $_POST['employee_data']);
 $query .= " FROM employeepersonelinfo where employeename = '" . 
 $_POST['employeename'] . "'";
 echo $query;
 ?>

You don't really need to check each and every value. You can save lines of code and lines of conditions by using array functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM