简体   繁体   English

从php中的mysql外键表中获取数据

[英]Fetch data from mysql Foreign key table in php

I have 3 tables in my database: 我的数据库中有3个表:

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). 我想知道如何从主表(tblclient和tblbranch)的tblclientbranch获取数据。

according to the database, one client can have many branches. 根据数据库,一个客户端可以有多个分支。 I want to fetch these both clientName and branchName into two dropdown menus. 我想将这两个clientName和branchName都提取到两个下拉菜单中。 If I select client name from dropdown, branchName dropdown able to show only branchName/s' of that specific user. 如果我从下拉列表中选择客户端名称,则branchName下拉列表仅能显示该特定用户的branchName / s。

Any solution would be great! 任何解决方案都很棒!
Thanks in Advanced. 提前致谢。

You need to use an SQL join here. 您需要在此处使用SQL连接。 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. 使用这样的查询,如果传入客户端ID#3,它将基于该ID在该表中查找客户端->分支连接,并返回该客户端连接到的所有分支。

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. 要回答有关下拉菜单的问题,您需要遍历所有用户并为每个用户返回一个包含其分支名称的数组,然后使用Javascript根据第一个下拉菜单中的选择填充第二个下拉菜单,或者使用AJAX调用绑定到第一个下拉列表的change事件以及在第一个下拉列表中所做的选择的 (您将使用该作为客户ID),以从上述查询中检索结果并以此填充第二个下拉列表。

Edit: here's a quick example in PHP and jQuery of how you might do this: 编辑:这是PHP和jQuery中的一个简单示例,说明如何执行此操作:

get_branches.php (access by AJAX, returns JSON) get_branches.php (通过AJAX访问,返回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: ...然后,您将使用jQuery(例如)绑定此select的change事件以填充另一个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. 确保在执行MySQL查询时在mysqli或PDO中使用参数绑定,以防止受到SQL注入等的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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