Best way to do mysql-query with dynamic values

Discussion in 'PHP' started by PoPSiCLe, Mar 27, 2009.

  1. #1
    Okay.

    I have a form, like this:

    
    <fieldset id="print_members"><legend><a href="javascript:toggleLayer('print_members_form');" title="Skriver ut medlemsliste">Skriver ut medlemsliste</a></legend>
    <form id="print_members_form" method="post" action="<?php echo "$domain"; ?>/index.php?page=print">
    <p class="warning">Her velger du hvilke elementer du vil ha med når medlemslisten skrives ut. Default er navn og epost, du kan også velge å ta med adresser, telefonnummer og fødselsdato.</p>
    <p class="left"><label>Navn:</label><input type="checkbox" name="pm_name" checked="checked" /></p>
    <p class="left"><label>Epost:</label><input type="checkbox" name="pm_email" checked="checked" /></p>
    <p class="left"><label>Adresser:</label><input type="checkbox" name="pm_address" /></p>
    <p class="left"><label>Telefonnummer:</label><input type="checkbox" name="pm_phone" /></p>
    <p class="left"><label>Fødselsdato:</label><input type="checkbox" name="pm_date" /></p>
    <p><input class="button" type="submit" value="Skriv ut medlemsliste" /></p>
    </form>
    
    Code (markup):
    Now, in the print-page, I would like to show what is gonna be printed, so the user can adjust the query or whatnot - that's no problem.

    What I'm pondering is how to make this as dynamical as possible, with as few lines of codes as possible.

    For every checked checkbox, another value is pulled from the database - so... how do I make a query just asking for the set variables... I'm probably missing something very simple here, but my brain is not functioning as intended today.

    Anyone have some tips as to how to check which variables are set, and then generate a dynamic query?
     
    PoPSiCLe, Mar 27, 2009 IP
  2. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I'm not sure I totally understand your question. But if I do, then you could do something like this:

    $fields = array('name', 'email', 'address');
    $fields_to_select = array();
    foreach ($fields as $f)
       if (isset($_REQUEST["pm_{$f}"]))
          $fields_to_select[] = $f;
    $sql = "select " . join(', ', $fields_to_select) . " from mytable";
    Code (markup):
    PS. I could be wrong, but I think <input type="checkbox"> requires a 'value' attribute.
     
    SmallPotatoes, Mar 27, 2009 IP
    PoPSiCLe likes this.
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    Hey! That worked, just had to tweak it a bit :)

    +rep added
     
    PoPSiCLe, Mar 27, 2009 IP