php best practise

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Barry Morris

    php best practise

    Hi

    I am a php newbie although I have been a programmer for years, this can be
    dangerous because all the languages I know use = as equal comparison so it
    took me a long time to debug if ($STRING = 'fred') { not realising I was
    assigning fred to $STRING and the evaluation is always true! It took ages to
    discover if ($STRING = = 'fred') {.

    I eventually managed to create a validated form which re-displays with an
    error list, but I have a few questions about 'best practise' programming
    because my solutions seem a little clumsy:

    Combobox selection: How do you set a default or remember what the user
    selected so the form is re-displayed with their selection. I did this: Item1
    = '< -- Select a Country --> as "selected", I then changed the text to the
    actual selection using echo if the form is re-displayed, Question: How do
    you dynamically set a default or dynamically move the SELECTED tag?

    <option selected><?echo $COUNTRY?></option>
    <option>Afghani stan</option>
    <option>Albania </option>
    <option>Algeria </option>


    Radio Buttons: I assigned each with a <? echoDEFAULT1 ?>, <? echo DEFAULT2
    ?> etc and set each to "" except for the default I really want, this is set
    to "checked", surely I am not doing this the right way?


    <input type="radio" value="MSWORD" <?echo $CKWORD?> name="RB1"
    tabindex="14">M icrosoft Word<br>
    <input type="radio" value="TXT" <?echo $CKTXT?> name="RB1"
    tabindex="15">T ext File<br>
    <input type="radio" value="PDF" <?echo $CKPDF?> name="RB1"
    tabindex="16">P ortable Document Format (PDF)</td>

    TIA

    Barry



  • rlee0001

    #2
    Re: php best practise

    Barry,

    For a combo box (drop-down select), use something like this:

    <label for='fld_locati on' accesskey='L'>< u>L</u>ocations:</label>
    <select id='fld_locatio n' name='location[]'>
    <?php
    // POPULATE LOCATIONS
    $locations = pg_query($db_co nn, 'SELECT name FROM locations ORDER BY
    name;');
    if ($locations) {
    while ($location = pg_fetch_object ($locations)) {
    echo '<option
    value=\''.$loca tion->name.'\''.(($l ocation->name==$thisrec ord->location)?'
    selected=\'sele cted\'':'').'>' .$location->name.'</option>';
    }
    }
    ?>
    </select>

    The ternary operator (cond?val1:val2 ) is used to check each option. If
    the option is the one currently selected output selected='selec ted',
    otherwise output an empty string. If you have a static list (as opposed
    to a database query), just put the ternary operator in each of the
    options checking each options value against the current selection.

    So the same thing in radio buttons using the ternary operator except
    use checked='checke d'. Hope that helped.

    -Robert

    Comment

    • Richard Levasseur

      #3
      Re: php best practise

      Best practice would be to use a class that encapsulates all of this,
      where the basic logic would be, more or less, in a simple model:
      Have a value that keeps the track of the selected item, an array of all
      the items, and a loop that checks if the currently outputted value is
      selected or not.

      in almost-correct-code:

      $options = array();
      $options['msword'] = 'MS Word';
      $options['txt'] = 'Text File';
      $selectedKey = null;

      echo "<selct bla bla>";
      foreach($option s as $key=>$value) {
      $selected = '';
      if($key == $selectedKey)
      $selected = 'selected';
      }
      echo "<option name='foo' value='$key' $selected>$valu e</option>"
      }
      echo "</select>"

      You can use the same procedure for radio buttons.

      Comment

      • Scott

        #4
        Re: php best practise

        Here's one way you can do that - have a function similar to this:

        function selectValue($na me,$value) {
        if(isset($_POST[$name]) && $_POST[$name] == $value) {
        return ' selected="selec ted"';
        } else {
        return '';
        }
        }

        Then, in your option list, do this:

        <select name="myOption" >
        <option<?=selec tValue('myOptio n','Option A');?>>Option A</option>
        <option<?=selec tValue('myOptio n','Option B');?>>Option B</option>
        </select>

        Scott

        Barry Morris wrote:[color=blue]
        > Hi
        >
        > I am a php newbie although I have been a programmer for years, this can be
        > dangerous because all the languages I know use = as equal comparison so it
        > took me a long time to debug if ($STRING = 'fred') { not realising I was
        > assigning fred to $STRING and the evaluation is always true! It took ages to
        > discover if ($STRING = = 'fred') {.
        >
        > I eventually managed to create a validated form which re-displays with an
        > error list, but I have a few questions about 'best practise' programming
        > because my solutions seem a little clumsy:
        >
        > Combobox selection: How do you set a default or remember what the user
        > selected so the form is re-displayed with their selection. I did this: Item1
        > = '< -- Select a Country --> as "selected", I then changed the text to the
        > actual selection using echo if the form is re-displayed, Question: How do
        > you dynamically set a default or dynamically move the SELECTED tag?
        >
        > <option selected><?echo $COUNTRY?></option>
        > <option>Afghani stan</option>
        > <option>Albania </option>
        > <option>Algeria </option>
        >
        >
        > Radio Buttons: I assigned each with a <? echoDEFAULT1 ?>, <? echo DEFAULT2
        > ?> etc and set each to "" except for the default I really want, this is set
        > to "checked", surely I am not doing this the right way?
        >
        >
        > <input type="radio" value="MSWORD" <?echo $CKWORD?> name="RB1"
        > tabindex="14">M icrosoft Word<br>
        > <input type="radio" value="TXT" <?echo $CKTXT?> name="RB1"
        > tabindex="15">T ext File<br>
        > <input type="radio" value="PDF" <?echo $CKPDF?> name="RB1"
        > tabindex="16">P ortable Document Format (PDF)</td>
        >
        > TIA
        >
        > Barry
        >
        >
        >[/color]

        Comment

        • Chung Leong

          #5
          Re: php best practise

          I do something similiar. For added flexibility, I pass the field value
          instead of the index into $_POST. I also have the function perform the
          echo.

          Here's the equivalent for checkboxes and radio buttons:

          function checked($curren t_value, $item_value) {
          if(is_array($cu rrent_value)) {
          $checked = in_array($item_ value, $current_value) ;
          }
          else {
          $checked = ($current_value == $item_value);
          }
          if($checked) {
          echo "checked";
          }
          }

          <input type="checkbox" <? checked($ck, 'hello') ?> name="ck[]"
          value="hello">

          Comment

          • fiziwig

            #6
            Re: php best practise

            I've been programming since the middle of the 20th century and I still
            type '=' when I mean '=='. One trick I learned is this:

            if ($string = 'fred') will NOT generate a syntax error.

            if ('fred' = $string) WILL generate a syntax error. You can't assign a
            variable to a constant.

            Put the constants first in compares and if it's not '==' it will warn
            you.

            That doesn't solve you larger problem, but it might help avoid one
            common debugging annoyance.

            --gary shannon

            Comment

            • Barry Morris

              #7
              Re: php best practise

              Thanks for the tips and example code. Are there any php books you can
              recommend?

              Barry


              Comment

              • Barry Morris

                #8
                Re: php best practise

                Thanks for that tip, I had a similar problem with syntax once before, I
                could not for the life of me work out why the Wang interpreter was throwing
                an error when I tried to display text in the middle of the screen. I had
                only just come from programming ICL VME computers (British) so no matter how
                hard I looked I could not see that CENTRE was spelt wrong. Good job the Wang
                was not in colour!



                Barry



                Comment

                • rlee0001

                  #9
                  Re: php best practise

                  Gary,

                  One thing about that is that it is counter-intuitive to read. For
                  example you are not asking "if 'fred' equals your name..." but rather
                  "if your name equals fred'...".

                  That said, your method is a very practical solution to a common
                  problem.

                  In a way I kinda wish that the '=' operator worked like the ECHO
                  construct in that you wouldn't be able to use it as a function. That
                  way if your source tried to actually look at the result of an '='
                  assignment a syntax error would occur (like the distinction between
                  echo and print). The only side effect would be that you would be unable
                  to chain assignments like this:

                  a = b = c = d = 0;

                  But an alternate method could be added to the language such as:

                  (a, b, c, d) = 0;

                  Which I think is actually used by LISP if I recall correctly.

                  But of course I'm just dreaming/thinking out loud here. :o)

                  -Robert

                  Comment

                  • David Haynes

                    #10
                    Re: php best practise

                    rlee0001 wrote:[color=blue]
                    > Gary,
                    >
                    > One thing about that is that it is counter-intuitive to read. For
                    > example you are not asking "if 'fred' equals your name..." but rather
                    > "if your name equals fred'...".
                    >
                    > That said, your method is a very practical solution to a common
                    > problem.
                    >
                    > In a way I kinda wish that the '=' operator worked like the ECHO
                    > construct in that you wouldn't be able to use it as a function. That
                    > way if your source tried to actually look at the result of an '='
                    > assignment a syntax error would occur (like the distinction between
                    > echo and print). The only side effect would be that you would be unable
                    > to chain assignments like this:
                    >
                    > a = b = c = d = 0;
                    >
                    > But an alternate method could be added to the language such as:
                    >
                    > (a, b, c, d) = 0;
                    >
                    > Which I think is actually used by LISP if I recall correctly.
                    >
                    > But of course I'm just dreaming/thinking out loud here. :o)
                    >
                    > -Robert
                    >[/color]

                    Why not change all the primitives to objects and then move the '='
                    operation to equal()? Then you could have:
                    $a->equal($b)

                    Or DEFINE the '=' to be '.equals.'? Then it would be:
                    $a .equals. $b

                    [Just joking. Programmers in other languages may recognize these.]

                    -david-


                    Comment

                    • Scott

                      #11
                      Re: php best practise

                      Are you using PHP 4 or 5?

                      I thought PHP and MySQL Web Development by Luke Welling and Laura
                      Thompson was a good book for learning PHP 4. I don't know if they have
                      a new edition out for PHP 5 yet. Make sure you don't get the 1st
                      edition of that book, though, because it was written before some of the
                      major changes to PHP 4 were out, such as register_global s disabled by
                      default.

                      Scott

                      Barry Morris wrote:[color=blue]
                      > Thanks for the tips and example code. Are there any php books you can
                      > recommend?
                      >
                      > Barry
                      >
                      >[/color]

                      Comment

                      Working...