Use button to change PHP variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PHPstarter
    New Member
    • Jun 2009
    • 77

    Use button to change PHP variable

    Was wondering how to do this?

    It's basically for a database table, so the button can be used to sort the results as ascending/descending.

    Googled a bit, but there wasn't much on it as I could see.
    Thanks
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    To change a server-side variable (in this case, PHP) from the client-side (browser), you generally pass a parameter in the URL of the page indicating the value. See the following:

    Code:
    <?php
    
    /** To obtain values from the URL, use the super-global GET array.
    if (isset($_GET['order']) && strlen($_GET['order']) > 0) {
        $order = $_GET['order']; // Read: SQL Injection
    } else {
        $order = "asc"; // Default to ascending.
    }
    
    printf("Selected order: %s", $order);
    If you're going to be using data that can be manipulated by the user in a database query, read up on SQL Injection.

    Comment

    • PHPstarter
      New Member
      • Jun 2009
      • 77

      #3
      Many thanks for the reply, will go ahead and test it out =)

      Comment

      • kovik
        Recognized Expert Top Contributor
        • Jun 2007
        • 1044

        #4
        Generally, empty() is the accepted way of performing both "isset()" and "strlen() > 0" at the same time.

        Also, since there are only two valid states of the query variable ("desc" and "asc"), it is considered more proper to treat is as a boolean (i.e. isdescending). Then you'd send the integer value 1 or 0 corresponding to true or false, respectively. This allows you to forcefully typecast the $_GET data to an integer, thus avoiding any SQL injection dangers.


        When you are using pagination (separating database data into pages) via server-side queries, then using a query variable for your database query is the best route. However, if you are retrieving all of the data items at once, then JavaScript may be a better choice to reduce page loads and database queries. Though, if you are unfamiliar with JavaScript and not interested in learning it yet, then stick with PHP.

        Comment

        • PHPstarter
          New Member
          • Jun 2009
          • 77

          #5
          Thanks for the detailed post, I'm gonna explore it and see how I can make this work as well :)

          thanks again

          Comment

          Working...