0

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?

2
  • Such a question smells of bad database design Commented Jun 6, 2013 at 14:58
  • 1
    a reason why this is such bad database design would be useful! Commented Jun 6, 2013 at 15:07

1 Answer 1

2

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';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.