I have an "access request" site where employees can enter a direct report or co-worker's name(s) and select a number of applications for them to gain access to. It's in PHP and the form/HTML looks like this.
<input type="text" name="employee_names[]" id="employee_name" autocomplete="off" />
Then the PHP processes the submission like this.
// process each request in the request
$employee_ids = $_POST['employee_names'];
// this can include multiple IDs, gotta parse each one
foreach($employee_ids as $employee_id) { this is where I do the stuff... }
The very first thing I do is attempt to query my employees db with the $employee_id as defined in the foreach.
$info = $db->query("SELECT *, CONCAT_WS(' ',IF(`preferred_first_name` IS NULL OR `preferred_first_name` = '', `first_name`, `preferred_first_name`),`last_name`) AS `FullName` FROM `db_name`.`table_name` WHERE `employee_id` = ".$db->escape_string($employee_id)." LIMIT 1")->fetch_assoc();
However, I always get the following error:
Call to a member function fetch_assoc() on bool
I do not get this error when I choose a single employee in the form, only when attempting to parse an array with multiple entries. When I troubleshoot by doing an "echo $employee_id" at the top of the foreach it is echoing a single comma-separated string of three or four employee IDs, and not a single ID, loop, next ID, loop, next ID, and et cetera.
Clearly the db query fails when multiple employees are selected because no such ID exists: employee_id_one,employee_id_two,employee_id_three...
My question is, what am I doing wrong on the form/HTML. I have other selections on the form that are coded the exact same way and they are all parsed just fine.
CodePudding user response:
When you use a name like employee_names[]
with a php backend, the PHP processor will create an array of all the elements in the form that share the same name.
You only have 1 element. Presumably, you are typing in the employee IDs, separated by commas. That's fine, but PHP isn't going to make that into an array for you.
If that's how you want it to work, then you don't need the [] on the name, and you need to split into an array yourself, using explode
<input type="text" name="employee_names" autocomplete="off" />
$employee_ids = explode(',',$_POST['employee_names']);