dynamic mysql SELECT qeury using checkboxes

Discussion in 'PHP' started by moneeshot, May 17, 2010.

  1. #1
    what I am trying to do is build a query using checkboxes
    The table will stay the same its the columns that the checkboxes will refer to.

    SELECT thisField, anotherField FROM members

    thisField of course would be one of the checkboxes, I guess it would have to check if box is checked then build the query from there

    any help would be greatly appreciated , this is killing me

    Moneehsot
     
    moneeshot, May 17, 2010 IP
  2. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #2
    Does any of this code make sense ?
    I don't want to explain anything unless I need to. :)

    <?php
    
    $expected_fields = array(
      'one' => true,
      'two' => true
    );
    
    $sql_fields = '';
    
    foreach((array)@$_POST['fields'] as $key => $val)
    {
      if( ! empty($expected_fields[$key]))
      {
        $sql_fields .= ",$key";
      }
    }
    
    if(strlen($sql_fields) > 0)
    {
      $sql = 'SELECT ' . substr($sql_fields, 1) . ' FROM ...';
      // run query
    }
    
    ?>
    Code (php):
    <input type="checkbox" name="fields[one]" value="1"/>
    <input type="checkbox" name="fields[two]" value="2"/>
    Code (markup):
     
    joebert, May 17, 2010 IP