I have a multiselect field
<select name="duration[]" id="duration" title="Duration" multiple="multiple" size="3">
<option value="1">1 Months</option>
<option value="2">2 Months</option>
<option value="3">3 Months</option>
</select>
my php code implode multiple values i.e 123 as 1,2,3 and insert it in database. The problem is that the field is not a required field and when i leave it empty it give me error (Invalid arguments passed)
My php code below
$duration = array();
$duration = $_POST['duration'];
if($duration)
{
foreach($duration as $value)
{
$months[] = $value;
}
}
$sql = "SELECT * FROM tbl_courses WHERE duration IN (".implode($months, ',').") ";
thanks in advance
The two problems you have is you try to implode on user input which may not be an array, and your code is vulnerable to SQL Injection.
To address those you should first check if it’s an array with
is_array(), then check if it has any elements withcount(), then finally implode but usearray_map()to filter the values to prevent SQL Injection. This will not only prevent SQL Injection but will prevent syntax errors in your query because strings must be quoted in anINclause.