简体   繁体   中英

Fetch data from mysql Foreign key table in php

I have 3 tables in my database:

1.tblclient
2.tblbranch
3.tblclientbranch


|____tblclient_____|      |______tblbranch____|      |___tblclientbranch___|
| clientId {PK}    |      | branchId {PK}     |      |  clientId {FK}      |
| clientName       |      | branchName        |      |  branchId {FK}      |
| clientMob        |      | branchAddress     |      |                     |
| clientEmail      |      |                   |      |                     |

I want to know how to fetch data from tblclientbranch of main tables (tblclient and tblbranch).

according to the database, one client can have many branches. I want to fetch these both clientName and branchName into two dropdown menus. If I select client name from dropdown, branchName dropdown able to show only branchName/s' of that specific user.

Any solution would be great!
Thanks in Advanced.

You need to use an SQL join here. An inner join would require a match to be made, which in the case of a "has many" would be correct. Try something like this:

SELECT B.* FROM tblbranch B
INNER JOIN tblclientbranch CB on CB.branchId = B.branchId
INNER JOIN tblclient C ON CB.clientId = C.clientId
WHERE C.clientId = [YOUR CLIENT ID HERE]

Using a query like this, if you pass in client ID #3, it will look for client -> branch connections in that table based on that ID, and return all branches that that client is connected to.

To answer your question about the dropdowns, you'd either need to loop through all your users and return an array for each of them containing their branch names then use Javascript to populate the second dropdown based on the selection from the first, or use an AJAX call bound to the change event of the first dropdown and the value of the selection made in the first dropdown (which you'd make your client ID) to retrieve the results from the above query and populate the second dropdown with that.

Edit: here's a quick example in PHP and jQuery of how you might do this:

get_branches.php (access by AJAX, returns JSON)

<?php
function getBranchesForClient($client_id) {
    // get the branches for a client

    $query = $pdo->prepare('SELECT B.* FROM tblbranch B INNER JOIN tblclientbranch CB on CB.branchId = B.branchId INNER JOIN tblclient C ON CB.clientId = C.clientId WHERE C.clientId = :client_id');
    $query->bindParam(':client_id', $client_id);
    $results = $query->execute();
    return $results->fetchAll(PDO::ASSOC);
}

echo json_encode(getBranchesForClient($_GET['client_id']));

So then you get your users, and you output a select box like this:

<select name="clients" id="clients">
    <?php
    foreach($clients as $client) {
        echo '<option value="' . $client['clientId'] . '">' . $client['clientName'] . '</option>';
    }
    ?>
</select>

You'd have a second select box like this for the branches:

<select name="branches" id="branches"></select>

... then you'll use jQuery (for example) to bind the change event of this select to populate the other select:

$('#clients').on('change', function() {
    var client_id = $(':selected', this).val();
    $.ajax({
        url: 'get_branches.php',
        data: { client_id: client_id },
        type: 'GET',
        dataType: 'JSON',
        success: function(msg) {
            // clear the select first
            $('#branch_select').empty();
            // add all new branches
            for(i in msg) {
                $('#branch_select').append('<option value="' + msg[i].branchId + '">' + msg[i].branchName + '</option>');
            }
        }
    });
});

There are many other ways to do this of course, this is just an example. Make sure you use parameter binding in mysqli or PDO when you're doing your MySQL query to be safe from SQL injection, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM