Jump to content

Barand

Moderators
  • Content Count

    19,099
  • Joined

  • Last visited

  • Days Won

    361

Posts posted by Barand


  1. Store the value from php into a hidden input field

    <?php
    
    $hidden_content = "Hello World";                                            // CREATE HIDDEN CONTENT
    ?>   
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="mytest.js"></script>
    </head>
    <body>
        <input type="hidden" id="my-hidden" value="<?=$hidden_content?>">        <!-- STORE HIDDEN CONTENT -->
    </body>
    </html>
    

    In your js file, get the value from the hidden input

        $().ready( function() {
            
            alert( $("#my-hidden").val())
            
        })

     


  2. Of course - no matter what value you pass, "1" is in the array so it returns "House". Functions exit as soon as a value is returned.

    Perhaps

    function property_structure_type ($data)
    {
        $types = [ 1 => 'House',
                   2 => 'Cabin',
                   3 => 'Mobile Home',
                   4 => 'Apartment',
                   5 => 'Condominium',
                   6 => 'Townhome'
                 ];
        return isset($types[$data]) ? $types[$data] : 'None';
    }
    
    echo property_structure_type(3);    //-> Mobile home

     


  3. This should be close to what you need

    <?php
    if (isset($_GET['city_id'])) {
        $where = [ "p.status != 'trashed'",  "paid = 1" ];
        $whereclause = '';
        $params = [];
        if ($_GET['city_id'] != 0) {
            $ids = explode(';', $_GET['city_id']) ;        // split multiple ids
            $k = count($ids);
            $placeholders = array_fill(0, $k, '?');
            $placestr = join(',', $placeholders);
            $where[] = "city_id IN ($placestr)";
            $params = $ids;
        }
        if (trim($_GET['query']) != '') {
            $where[] = "MATCH(place_name, description) AGAINST (?)";
            $params[] = $_GET['query'];
        }
        $whereclause = "WHERE " . join(' AND ', $where);
        
        // FIND HOW MANY RECORDS FOR PAGINATION
        $res = $conn->prepare("SELECT COUNT(*)
                             FROM cities c
                             JOIN places p USING (city_id)
                             $whereclause
                            ");
        $res->execute( $params );
        $total_rows = $res->fetchColumn();
        
        // NOW GET THE RECORDS FOR DISPLAY
        $rows_per_page = 10;
        $total_pages = ceil($total_rows/$rows_per_page);
        $page = $_GET['page'] ?? 1;
        $offset = ($page - 1) * $rows_per_page;
        
        $res = $conn->prepare("SELECT c.city_name
                                  , c.state
                                  , p.place_id
                                  , p.place_name
                                  , p.lat
                                  , p.lng
                                  , p.description
                              FROM cities c
                              JOIN places p USING (city_id)
                              $whereclause
                              ORDER BY city_name, place_name
                              LIMIT $offset, $rows_per_page
                            ");
        $res->execute( $params );
        
        // OUTPUT  YOUR RESULTS HERE
    }
    ?>
    <hr>
    <form>
    City <select id="query-input" name="city_id" required>
            <option value="">Select Area</option>
            <option value="3;1">Ches & VB</option>
            <option value="3">Chesapeake , VA</option>
            <option value="9">Hampton , VA</option>    
            <option value="10">Newport News , VA</option>            
            <option value="2">Norfolk , VA</option>            
            <option value="12">Poquoson , VA</option>    
            <option value="4">Portsmouth , VA</option>                
            <option value="5">Suffolk , VA</option>                
            <option value="1">Virginia Beach , VA</option>    
            <option value="11">Williamsburg , VA</option>
            <option value="0">All Active US Cities</option>
            </select>
    <br>        
    Search for <input type="text" name="query" value="">
    <input type="submit" name="btnSub" value="Search">
    <br>

     


  4. 52 minutes ago, JoseN said:

    is it best practices to not store calculated values in a database?

    That's the general theory (however, as with any rule, there may be exceptions in practice. For example, I expect my bank stores the closing balance on my last statement, otherwise it will have to go through 50 years of transactions to get the opening balance on my next statement). Storing the individual transactions that build up to the total gives you an audit trail. There is also a possibility that a stored total could get out of sync with the total of the individual transactions, and then you have two versions of the "truth".


  5. 1 hour ago, JoseN said:

    $query = "UPDATE users usertable INNER JOIN (SELECT userID, SUM(pointsEarned) as totalpoints FROM points GROUP BY userID) pointstable ON usertable.userID = pointstable.userID SET usertable.TotalPoints = pointstable.totalpoints";

    Don't store totals (or any other derived data) in your tables. You get totals by requerying your data when required.

    You have a INSERT ... SELECT query. If you run the SELECT portion on its own, do you only get a single record every time?


  6. Something like this, perhaps

    TEST DATA

    +----+-----------+--------------+------------+
    | id | name      | date_started | days_count |
    +----+-----------+--------------+------------+
    |  1 | Contest 1 | 2019-04-16   |          1 |
    |  2 | Contest 2 | 2019-04-15   |          3 |
    |  3 | Contest 3 | 2019-04-14   |          5 |
    |  4 | Contest 4 | 2019-04-14   |          2 |
    |  5 | Contest 5 | 2019-04-15   |          1 |
    +----+-----------+--------------+------------+

    QUERY

    SELECT name
         , date_started as startdate
         , date_started + INTERVAL days_count-1 DAY as enddate
         , datediff(curdate(), date_started) + 1 as daynum
    FROM contests
    WHERE curdate() BETWEEN date_started AND date_started + INTERVAL days_count-1 DAY
    ORDER BY date_started;

    RESULTS

    +-----------+------------+------------+--------+
    | name      | startdate  | enddate    | daynum |
    +-----------+------------+------------+--------+
    | Contest 3 | 2019-04-14 | 2019-04-18 |      3 |
    | Contest 2 | 2019-04-15 | 2019-04-17 |      2 |
    | Contest 1 | 2019-04-16 | 2019-04-16 |      1 |
    +-----------+------------+------------+--------+

     


  7. "data-" attributes are useful, EG

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $().ready( function() {
            
            $(".redeem").click( function() {
                var pts = $(this).val()
                var userid = $(this).data("id")
                alert("User: " + userid + "\nPoints: " + pts)
            })
        })
    </script>
    </head>
    <body>
    
    <button class='redeem' data-id='42' value='10' >Redeem</button>
    <button class='redeem' data-id='25' value='30' >Redeem</button>
    </body>
    </html>

     


  8. When I decoded and used print_r I got this

     $data Array
    (
        [0] => Array
            (
                [id] => 1
                [package_name] => 1 Month Full + Adult - 2 Devices
                [is_trial] => 0
                [is_official] => 1
                [trial_credits] => 0
                [official_credits] => 1
                [trial_duration] => 24
                [trial_duration_in] => hours
                [official_duration] => 1
                [official_duration_in] => months
                [groups] => [4,5,6,8]
                [bouquets] => [27]
                [can_gen_mag] => 1
                [only_mag] => 0
                [output_formats] => [1,2,3]
                [is_isplock] => 0
                [max_connections] => 2
                [is_restreamer] => 0
                [force_server_id] => 0
                [can_gen_e2] => 1
                [only_e2] => 0
                [forced_country] => 
                [lock_device] => 0
            )
    
    )

    If he didn't see it there it's unlikely a var_dump would have clarified things


  9. It would only make sense if the "[ ]" contained a key value.

    $array = [ 'First', 'Second', 'Third'];
    $array[0] .= " item";                      // now you can use the concatenation operator
    
    echo '<pre>', print_r($array, 1), '</pre>';
     /* OUTPUTS
             Array
            (
                [0] => First item
                [1] => Second
                [2] => Third
            )
    */

    However,

    $array[] .= " item";        // surprisingly it works!

     


  10. How do you know it is only pulling one city and not both? You only do a single fetch().

    Where it says "// process the ststement results here" try

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $query_city_name = $row['city_name'];
        $query_state_abbr = $row['state'];
        echo "$query_city_name, $query_state_abbr<br>";
    }

     


  11. Here's a method for handling IN(...) with prepared statements.

    <?php
    if (isset($_GET['city_id'])) {
        if ($_GET['city_id'] != 0) {
            $ids = explode(';', $_GET['city_id']) ;        // split multiple ids
            $k = count($ids);
            $placeholders = array_fill(0, $k, '?');
            $placestr = join(',', $placeholders);
            $stmt = $conn->prepare("SELECT city_name, state FROM cities WHERE city_id IN ($placestr)");
            $stmt->execute($ids); 
        }
        else {
            // if you want all cities then a where clause is not needed
            $stmt = $conn->query("SELECT city_name, state FROM cities");        
        }
        // process the stmt results here
    }
    ?>
    <html>
    <body>
        <form>
            <select id="query-input" name="city_id" style="width:28.8%" style="height:69px" required>
                                            
            <option value="">Select Area</option>
                        
            <option value="3;1">Ches & VB</option>
            <option value="3">Chesapeake , VA</option>
            <option value="9">Hampton , VA</option>    
            <option value="10">Newport News , VA</option>            
            <option value="2">Norfolk , VA</option>            
            <option value="12">Poquoson , VA</option>    
            <option value="4">Portsmouth , VA</option>                
            <option value="5">Suffolk , VA</option>                
            <option value="1">Virginia Beach , VA</option>    
            <option value="11">Williamsburg , VA</option>
            <option value="0">All Active US Cities</option>
            </select>
            <input type="submit" name="btnSub" value="Submit">
        </form></body>
    </html>

     

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.