Asked  8 Months ago    Answers:  5   Viewed   29 times

Continent Table

  1. ASIA

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>"; } ?>

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>"; } ?>

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


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;
                // the next thing you want to do 


in my function the php

function Country(){
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?


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.



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
            //in here, for simplicity, you can substitue the HTML for a brand new select box for countries

           // 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
answered 8 Months ago

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
answered 8 Months ago

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:

    if ($(this).val() == "credit") {
    } else {

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

window.addEvent('domready', function(){
    if($(this).get('value') == 'credit') {
    } else {

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
answered 8 Months ago

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>


    $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' ){


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

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


                $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->bind_result( $srn, $instruction );

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

                header('Content-Type: text/html');
                echo implode( PHP_EOL, $html );
        }catch( Exception $e ){
            echo $e->getMessage();
<!doctype html>
        <title>Dependent / Chained SELECT menus</title>
            /* AJAX FUNCTION */
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                    if( xhr.readyState==4 && xhr.status==200 ) 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;

       m.toUpperCase(), u, true );
                xhr.send( p );

            /* AJAX CALLBACK */
            function createmenu(r,o,h){

            function get_nextsibling(n){
                while ( x.nodeType!==1 ) x=x.nextSibling;
                return x;

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

                    var method='post';
                    var url=location.href;
                    var params={
                    var td=get_nextsibling( el.parentNode );
                    var oSelect=td.querySelector('select');

                    var opts={
           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 ){
                        /* get a reference to the first & last row, of class "item", in table */
                        var tr=tbl.querySelectorAll( 'tr.items' )[0];
                        var ref=tbl.querySelector( '' );

                        /* 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 */

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

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
answered 5 Months ago

You can use the BETWEEN clause:

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:

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:

Saturday, May 29, 2021
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 :