Reputation: 4111
I am trying to build a PHP PDO query, based from a set of checkboxes that a user has selected on the previous page.
So i have the following checkboxes in my form:
<input type="checkbox" name="websites[]" value="one" id="one">
<input type="checkbox" name="websites[]" value="two" id="two">
<input type="checkbox" name="websites[]" value="three" id="three">
Once submitted i then want to build a pdo query and query parameters based from what checkboxes the user selected - they have to all be in the one query though. I know that any checked boxes will be stored in my $_POST['website'] array but how can i then take that and put them in the query? For example say the user selected one and three only, i then want to only select those fields from my database table:
$results = $_POST['websites'];
$query = "
SELECT
one,
three
FROM
table
";
How can i do the above?
Upvotes: 0
Views: 1197
Reputation: 91762
First of all you should use a white-list of allowed fields to avoid sql injection. Then you need to check every sent-in entry to see if it exists in your white-list and add it to the query if it does.
So something like:
$allowed_fields = array(...);
$fields = array();
// only checked fields are sent to the server
foreach ($_POST['websites'] as $value)
{
if (in_array($value, $allowed_fields))
{
$fields[] = $value;
}
}
$query = 'SELECT `' . implode('`, `', $fields) . '` FROM table';
Upvotes: 2