Asked  8 Months ago    Answers:  5   Viewed   29 times

Continent Table

  1. ASIA
  2. SOUTH AMERICA

Country Table

  1. Japan
  2. China
  3. Brazil
  4. Peru

This is the data in my table and i get all the data from continent table and country table like this

    <select name="continent" class='required InputBox'>
          <?php echo "<option value=''></option>"; 
    foreach (Contintent() as $value) { 
echo "<option id='" . $value[ 'sysid'] . "' value='" . $value[ 'name'] . "'>" . $value[ 'name'] . "</option>"; } ?>
        </select>

This is for country

<select name="country" class='required InputBox'>
              <?php echo "<option value=''></option>"; 
        foreach (Country() as $value) { 
    echo "<option id='" . $value[ 'sysid'] . "' value='" . $value[ 'name'] . "'>" . $value[ 'name'] . "</option>"; } ?>
            </select>

I want to know how to make it in a way that when i select the continent for example asia the option available for county will be the country in asia only which is japan and china. I also have another table after this which is city but if i get the logic here i can apply it to city. Any idea is appreciated

"UPDATE"

Found something here

One that i am not familiar with is the ajax can anybody try to explain how it work i want to know how i can pass the id of the select from this javascript snippet to my php function page here is the snippet..

$('.continent').change(function() {
        var id = $(this).find(':selected')[0].id;
        //alert(id); 
        $.ajax({
            type:'POST',
            url:'../include/functions.php',
            data:{'id':id},
            success:function(data){
                // the next thing you want to do 
console.log(data);
                alert(id);
            }
        });

    });

in my function the php

function Country(){
if(isset($_POST['id'])){
echo $_POST['id'];
}
}

The problem is the value of id is not passed how do i pass it onto the function.php i kind of out of idea here. Does it happened in success:function(data){ what do i do next?

FYI

The alert is ok it gets the id of the continent already it is just not passed to the function.php and console.log writes nothing and when i change the url to main page the page where the select are in the console.log returns the main page code.

 Answers

44

Like it was said, you can use ajax. There is a static non-ajax way of doing it, but this way it is better in the long run.

Basically, what you do with that jQuery is listen for a change in the continent select box, and when a change happens, you make a request to the server asking: "give me all the countries within this continent". You should have a database for this or you can map them in static objects just to test it out.

$('.continent').change(function() {
    var id = $(this).val(); //get the current value's option
    $.ajax({
        type:'POST',
        url:'<path>/getCountries',
        data:{'id':id},
        success:function(data){
            //in here, for simplicity, you can substitue the HTML for a brand new select box for countries
            //1.
            $(".countries_container").html(data);

           //2.
           // iterate through objects and build HTML here
        }
    });
});

This would of course make you add the countries_container in the HTML like and inside it you would render the select:

<div class="countries_container"></div>

Now in the actual PHP code server side (getCountries) you could do something like:

$id = $_POST['id'];
if(isset($id) && <other validations>)){

  // 1. your query to get countries from a given continent
  // and for each result you can build the HTML itself

  // 2. OR, a better solution is to return an Object and then in the
  // success:function(data){ } iterate through it
}

This code can most defiantly be improved, but I tried to explain it in a understandable way.

Also, you should check:

Jquery ajax populate dropdown with json response data

Demo of linked drop down list by using Ajax & PHP

Keep on mind, these were the first results from a google search therefore, next time, try to search within stack overflow itself to avoid duplicate questions.

Wednesday, March 31, 2021
 
freeMagee
answered 8 Months ago
31

Create each of the name="something4" into an array like this:

<input name="something4[]" type="text" />

Then you can do a

foreach($_POST['something4'] as $something4) {
}
Wednesday, March 31, 2021
 
MDDY
answered 8 Months ago
58

It's not possible to do such thing with PHP only, because PHP is run on your server. You need some code that is run on the client.

I believe that the first paramater $id is used as id attribute for the elements? If I'm wrong correct me. If so you can do the following using the jQuery JavaScript Library:

jQuery(function($){
  $('#type').change(function(){
    if ($(this).val() == "credit") {
      $('#paid').attr('checked','checked');
    } else {
      $('#paid').removeAttr('checked');
    }
  });
});

UDPATE BMS is using Mootools, the JavaScript should like like this to work in mootools:

window.addEvent('domready', function(){
  $('type').addEvent('change',function(){
    if($(this).get('value') == 'credit') {
      $('paid').set('checked','checked');
    } else {
      $('paid').removeProperty('checked');
    }
  });
});

I would recommend using the mootools version of this snippet, but just for your interest, if you want to install jQuery, you can add the jquery.js into phpbms/common/javascript. Then you can edit phpbms/header.php to include this:

after the last $tempjsarray[] add:

$tempjsarray[] = "common/javascript/jquery.js";

then after $phpbms->showJsIncludes(); you need to include this, so jQuery works without problems besides mootools:

echo '<script type="text/javascript">jQuery.noConflict();</script>';

If this doesn't work, you should post what the html output looks like.

Wednesday, March 31, 2021
 
o_flyer
answered 8 Months ago
69

In your code above you are running the same query twice which I presume is a copy/paste mistake?

What follows is based upon previous question and help already offered.

mysql> describe irn_item;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| irn   | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(50)      | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+


mysql> select * from irn_item;
+-----+------------+
| irn | name       |
+-----+------------+
|   1 | Shirt      |
|   2 | Trousers   |
|   3 | Jacket     |
|   4 | Socks      |
|   5 | Underpants |
|   6 | Hat        |
+-----+------------+


mysql> describe irn_service;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| srn         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| irn         | int(10) unsigned | NO   | MUL | 1       |                |
| instruction | varchar(50)      | NO   |     | 1       |                |
+-------------+------------------+------+-----+---------+----------------+


mysql> select * from irn_service;
+-----+-----+-----------------------+
| srn | irn | instruction           |
+-----+-----+-----------------------+
|   1 |   2 | Iron                  |
|   2 |   1 | Dry Clean Only        |
|   3 |   3 | Hi-Pressure dry clean |
|   4 |   4 | Steam Clean           |
|   5 |   5 | Decontaminate         |
|   6 |   6 | Waterproof            |
+-----+-----+-----------------------+

Without knowing the schema of the database I made up a quick example database based upon some of the columns seen in the sql in the original code. The code below uses mysqli rather than PDO simply because for my testing it is much quicker to write so please ignore the fact that it does not follow exactly. The important aspect that you are having troubles with, I believe, is that newly added rows do not copy the event handler which triggers the ajax request. I did make mention yesterday that when cloning nodes any event handlers assigned using addEventListener will NOT be copied/cloned - so to ensure that event handlers are copied/cloned you need to use inline event handlers ~ ie: <select onchange='evtselect(event)'>...</select>

<?php

    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'xxx';
    $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );



    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){

        ob_clean();

        try{
            $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );

            if( $id && !empty( $id ) ){

                $html=array();

                $sql='select `srn`,`instruction` from `irn_service` where `irn` = ? order by `srn` asc';
                $stmt=$db->prepare( $sql );

                if( $stmt ){
                    $stmt->bind_param( 's', $id );
                    $stmt->execute();
                    $stmt->store_result();
                    $stmt->bind_result( $srn, $instruction );


                    while( $stmt->fetch() ){
                        $html[]="<option value='{$srn}'>{$instruction}";
                    }
                    $stmt->close();
                }

                header('Content-Type: text/html');
                echo implode( PHP_EOL, $html );
            }
        }catch( Exception $e ){
            echo $e->getMessage();
        }
        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <title>Dependent / Chained SELECT menus</title>
        <script>
            /* AJAX FUNCTION */
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }


            /* AJAX CALLBACK */
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            /* UTILITY TO FIND NEXT SIBLING ELEMENT NODE */
            function get_nextsibling(n){
                x=n.nextSibling;
                while ( x.nodeType!==1 ) x=x.nextSibling;
                return x;
            }

            /* INLINE EVENT HANDLER */
            function evtselect(e){
                try{
                    var el=e.target;
                    if( el.value=='null' || el.value==null )return false;

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':el.value
                    };
                    var td=get_nextsibling( el.parentNode );
                    var oSelect=td.querySelector('select');

                    var opts={
                        menu:oSelect
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }catch( err ){
                    console.log( err );
                }
            }


            function bindEvents(){

                var bttn=document.querySelector('input[name="add"]');
                var tbl=document.querySelector('form#item_sel > table');

                if( bttn && tbl ){
                    bttn.addEventListener('click',function(e){
                        /* get a reference to the first & last row, of class "item", in table */
                        var tr=tbl.querySelectorAll( 'tr.items' )[0];
                        var ref=tbl.querySelector( 'tr.save' );

                        /* Create a clone of the entire row - which includes the inline event handlers */
                        var clone=tr.cloneNode( true );

                        /* Insert the new row after the last row */
                        tr.parentNode.insertBefore( clone, ref );

                        /* Ensure that newly added "service" select menu is empty */
                        clone.querySelector('select[name="item[]"]').value='null';
                        clone.querySelector('select[name="service[]"]').innerHTML='';
                        clone.querySelector('input[name="qty[]"]').value='';

                    },{ capture:false, passive:true, once:false } );                    
                }
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents, false );
        </script>
        <style type='text/css' charset='utf-8'>
            select {padding:1rem;width:300px;}
        </style>
    </head>
    <body>
        <h1>Chained select menus using basic ajax</h1>
        <form method='post' id='item_sel'>
            <table>
                <tr class='headers'>
                    <th scope='col'>Item</th>
                    <th scope='col'>Service</th>
                    <th scope='col'>Qty</th>
                </tr>
                <tr class='items'>
                    <td>
                        <select name='item' class='country' onchange='evtselect(event)'>
                            <option value=null>Please Select
                        <?php
                            $sql='select * from `irn_item` order by `irn`;';
                            $result=$db->query( $sql );
                            $html=array();
                            if( $result ){
                                while( $rs=$result->fetch_object() ){
                                    $html[]="<option value='{$rs->irn}'>{$rs->name}";
                                }
                                echo implode( PHP_EOL, $html );
                            }
                        ?>
                        </select>                       
                    </td>
                    <td><select name='service' class='country'></select></td>
                    <td><input type='number' name='qty' min=0 max=1000 /></td>
                </tr>
                <tr class='save'>
                    <td colspan='3'>
                        <button type='submit' name='btnsave' class='btn btn-default'>
                            <span class='glyphicon glyphicon-save'></span> &nbsp; Save
                        </button>
                    </td>
                </tr>
            </table>
            <input name='add' type='button' class='add-row' value='Add Row' />
        </form>
    </body>
</html>

With this code I took the trouble of renaming newly added elements - this is probably not strictly necessary as you could instead use array syntax for the element names - viz: <select name='item[]' onchange='evtselect(event)> or <input type='number' name='qty[]' /> etc then access the appropriate values in PHP in the usual manner. It should be mentioned that if you decide upon that approach (ie array syntax ) then you would need to look at the various selectors used in the javascript and edit the names appropriately.

I trust that with this new insight into the use of inline event handlers that you should be able to nail the problem you have - you can, with a little minor editing of this code, run it for yourself to see the application working correctly. You should edit the table names (irn_item -> item, irn_service -> service ) and add suitable db/pwd details... Good luck

Saturday, May 29, 2021
 
clean_coding
answered 5 Months ago
15

You can use the BETWEEN clause:

http://www.tutorialspoint.com/mysql/mysql-between-clause.htm https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between

SELECT dateCol FROM tableName WHERE dateCol BETWEEN '2015-05-01' AND '2015-05-27';

Almost any info about SQL syntax for MySQL can be found on MySQL dev site: https://dev.mysql.com/doc/

To get the values from you form fields you will have to use $_GET["field_name"] or $_POST["field_name"] values acoording to the value of your form's method attribute. The values will be available when you submit the form.

$startdate = $_POST["startdate"];

As an advice, avoid concatenating user values in you queries. Or else, you will open your app for SQL injection.

Take a look at mysqli functions (yes, with an "i" at the end) or, even better, PDO:

http://php.net/manual/book.mysqli.php
http://php.net/manual/book.pdo.php

Saturday, May 29, 2021
 
jwegner
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :